基本上你正在尋找一個監視器的過程,它會運行一個命令(或命令集),並觀看他們的執行尋找具體的事情(在你的情況下,stdout
沉默)。引用2所以下面的問題(和一些文檔簡單的介紹一下),您可以快速構建一個超級簡單的監控。
https://stackoverflow.com/questions/2804543/read-subprocess-stdout-line-by-line https://stackoverflow.com/questions/3471461/raw-input-and-timeout
# monitor.py
import subprocess
TIMEOUT = 10
while True:
# start a new process to monitor
# you could also run sys.argv[1:] for a more generic monitor
child = subprocess.Popen(['python','other.py','arg'], stdout=subprocess.PIPE)
while True:
rlist,_,_ = select([child.stdout], [], [], TIMEOUT)
if rlist:
child.stdout.read() # do you need to save the output?
else:
# timeout occurred, did the process finish?
if child.poll() is not None:
# child process completed (or was killed, but didn't hang), we are done
sys.exit()
else:
# otherwise, kill the child and start a new one
child.kill()
break