我有使用while循環和睡眠像下面蟒子輪詢()沒有返回無即使POPEN仍在運行
fout = tempfile.TemporaryFile()
try:
p = subprocess.Popen(["/bin/bash","-c", options.command], bufsize=-1, shell=False, preexec_fn=os.setsid, stdin=subprocess.PIPE, stdout=fout, stderr=subprocess.PIPE)
except:
sys.exit(UNEXPECTED_ERROR)
if options.timeout:
print "options.timeout = %s" % options.timeout
elapsed = 0
time.sleep(0.1) # This sleep is for the delay between Popen and poll() functions
while p.poll() is None:
time.sleep(1)
elapsed = elapsed + 1
print "elapsed = %s" % elapsed
if elapsed >= options.timeout:
# TIMEDOUT
# kill all processes that are in the same child process group
# which kills the process tree
pgid = os.getpgid(p.pid)
os.killpg(pgid, signal.SIGKILL)
p.wait()
fout.close()
sys.exit(TIMEOUT_ERROR)
break
else:
p.wait()
fout.seek(0) #rewind to the beginning of the file
print fout.read(),
fout.close()
sys.exit(p.returncode)
$ time myScript -c "cat file2" 2>&1 -t 5
options.timeout = 5
elapsed = 1
real 0m11.811s
user 0m0.046s
sys 0m1.153s
我的問題是在這上面超時執行的Linux命令的python腳本即使超時時間爲5秒,貓也會一直持續到完成。我在這裏錯過了什麼嗎?請幫忙。
我與Python 2.4.3 – yalkris
上RHEL5.5運行,我認爲有可能是'cat'把所有的數據輸出流中,但你的終端是讀它太慢所有。如果你嘗試像下面這樣的命令會發生什麼:'while:;做回聲「嗨」;睡1;完成'? – mgilson
你能詳細介紹一下你看到的內容嗎?你粘貼的輸出看起來像循環第一次運行後退出的while循環。它似乎沒有進入超時代碼。 –