使用一个简单的线程化Timer()来终止超时的子proc时,直接调用proc.kill可以按预期方式工作,但是通过另一个回调调用proc.kill则无法正常工作。回调已执行但subproc没有被杀死?
from subprocess import Popen, PIPE
from threading import Timer
def pkill(p):
pid = p.pid
print("Killing process pid=[%s]\n" % (pid))
p.kill
def run(cmd, timeout_sec):
print("Popen() for cmd=[%s]\n" % (command))
proc = Popen(shlex.split(cmd), stdout=PIPE, stderr=PIPE)
pid = proc.pid
print("Starting subprocess with pid=[%s]\n" % (pid))
## works as expected when kill called directly
timer = Timer(timeout_sec, proc.kill )
## doesn't work when given to a callback
## timer = Timer(timeout_sec, pkill, [proc] )
try:
print("Starting timer() for [%d] seconds\n" % (timeout_sec))
timer.start()
stdout, stderr = proc.communicate()
finally:
timer.cancel()
run("sleep 5", 1)