Pythonのcgiで別プロセスを呼び出す際にはまったこと
やりたいこと
WEBアクセスに応じて、プロセスをたちあげて処理を開始する。
プロセスをたちあげたらレスポンスを返す(プロセスの終了を待たずにレスポンスを返す)
うまくいかなかった例
別プロセスとして、以下のPythonスクリプトを呼び出すケースを考えます
mytask.py
import time time.sleep(20)
以下のCGIスクリプトで処理をしようとしました。
test.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- import subprocess devnull = open('/dev/null', 'w') subprocess.Popen(["python3", "mytask.py"], close_fds=True, stdout=devnull, stderr=devnull) print("Content-Type: text/html") print("") print("OK")
さて、このスクリプトを
python3 test.py
と実行するとすぐに処理がおわり、psコマンドでpython3 test.pyのプロセスが走っていることが確認できます。
では、これでOKかと思いきや、CGIでtest.pyを呼び出すと20秒ほど応答が返ってきません。
Apacheか何かがすべての処理が終わるのを待っているようです。
対策
色々試した結果ですが、Popenの個所を以下のようにしたら、CGI経由でも意図通りに動きました。
subprocess.Popen("nohup python3 mytask.py &", shell=True, close_fds=True, stdout=devnull, stderr=devnull)