[英]How to send terminate signal to the child process on exception, when using subprocess
我正在通過子進程從另一個python程序運行python progam,我這樣稱呼它。
try:
subproc = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE,
shell=True)
o, e = subproc.communicate()
sys.stdout.write(o)
sys.stderr.write(e)
except:
subproc.terminate()
在被調用的程序中,我注冊了如下所示的信號處理程序。 但是,盡管調用了終止函數,但在上面的程序中永遠不會在異常上調用它。 但是,如果我單獨運行子程序,則handle_exit
函數會正常運行。 我在這里做什么錯?
def handle_exit(sig, frame):
print('\nClean up code here)
....
signal.signal(signal.SIGTERM, handle_exit)
signal.signal(signal.SIGINT, handle_exit)
更新:好的,我通過將subproc.terminate
替換為以下內容來使其工作。
subproc.send_signal(signal.SIGINT)
subproc.wait()
很好,但是我也想獲取異常子進程的輸出。 我該怎么辦?
我找到了解決方案,就在這里。
try:
subproc = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE,
shell=True)
o, e = subproc.communicate()
except:
subproc.send_signal(signal.SIGINT)
o, e = subproc.communicate()
sys.stdout.write(o)
sys.stderr.write(e)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.