subprocess.Popen.poll()で起動しているサブプロセスが動いているとき,
異常を検知した時に,サブプロセスを生成し直す方法をご教授ください。
以下のようにサブプロセスの中でKeyboardInterruptを発生させて,
親でそれをキャッチできないかと考えたのですがうまくいきませんでした。
親のモジュール(main.py)
python
1import os 2import sys 3import time 4import subprocess 5 6while True: 7 # 非同期でtest.pyを起動しておきたい 8 proc = subprocess.Popen(['python', 'test.py']) 9 proc.poll() 10 try: 11 # 一定時間でsubprocessを生成し直すようにしている 12 time.sleep(60) 13 except KeyboardInterrupt: 14 # main.pyを最初からやり直す 15 os.execlp('python, 'main.py') 16 # もしくはwhileループをやり直して 17 # subprocessを生成し直したい
子のモジュール(test.py)
python
1import time 2 3print('start') 4time.sleep(1) 5print('end') 6raise KeyboardInterrupt
実行結果
キーボードからCtl-Cを入力するとキャッチできたのですが,
test.pyからのKeyboardInterruptはキャッチされませんでした。
>python mian.py start end Traceback (most recent call last): File "test.py", line 6, in <module> raise KeyboardInterrupt KeyboardInterrupt # ←test.pyのKeyboardInterrupt catch # ←キーボードからCtl-C start # ←再生成 end Traceback (most recent call last): File "print.py", line 6, in <module> raise KeyboardInterrupt KeyboardInterrupt
ちなみにtest.pyはwebサーバのようなもので,
常にリクエストを待っている状態で,
returnして終了させることができないので,
何らかの方法で親に対してsubprocessの再生成を指示したいです。
よろしくお願い致します。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/02/08 22:02