我想知道当杀死在不同线程中启动的子进程时是否可以关闭通信管道。如果我不调用communicate(),那么kill()将按预期工作,在一秒而不是五秒后终止进程。
我发现了类似问题的讨论here http://bugs.python.org/issue4216,但我没有得到真正的答案。我假设我必须能够关闭管道或显式终止子子进程(在示例中为“睡眠”)并终止它以解锁管道。
我也试图在SO上找到她的答案,但我只找到了this https://stackoverflow.com/questions/1603658/kill-subprocess-when-python-process-is-killed and this https://stackoverflow.com/questions/1180606/using-subprocess-popen-for-process-with-large-output and this https://stackoverflow.com/questions/320232/ensuring-subprocesses-are-dead-on-exiting-python-program,据我所知,这并没有直接解决这个问题(?)。
因此,我想做的事情是能够在第二个线程中运行命令并获取其所有输出,但能够在我需要时立即终止它。我可以通过一个文件并尾部该文件或类似的文件,但我认为应该有更好的方法来做到这一点?
import subprocess, time
from threading import Thread
process = None
def executeCommand(command, runCommand):
Thread(target=runCommand, args=(command,)).start()
def runCommand(command):
global process
args = command.strip().split()
process = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE)
for line in process.communicate():
if line:
print "process:", line,
if __name__ == '__main__':
executeCommand("./ascript.sh", runCommand)
time.sleep(1)
process.kill()
这是脚本:
#!/bin/bash
echo "sleeping five"
sleep 5
echo "slept five"
Output
$ time python poc.py
process: sleeping five
real 0m5.053s
user 0m0.044s
sys 0m0.000s