python Popen:我如何停止(杀死)使用Popen创建的子进程?
问题描述:
我需要停下来,我通过POPEN发行的蟒蛇,我得到了结果后服务(运行在另一个线程的背景),但下面的方法失败(只使用ping
为便于说明):python Popen:我如何停止(杀死)使用Popen创建的子进程?
class sample(threading.Thread):
def __init__(self, command, queue):
threading.Thread.__init__(self)
self.command = command;
self.queue = queue
def run(self):
result = Popen(self.command, shell=True, stdout=PIPE, stderr=STDOUT)
while True:
output = result.stdout.readline()
if not self.queue.empty():
result.kill()
break
if output != "":
print output
else:
break
def main():
q = Queue()
command = sample("ping 127.0.0.1", q)
command.start()
time.sleep(10)
q.put("stop!")
command.join()
if __name__ == "__main__":
main()
运行上面的程序后,当我pgrep为ping
,它仍然存在。我怎样才能杀死Popen打开的子进程?谢谢。
PS:我也尝试过result.terminate(),但并没有真正解决问题。
答
你并不需要从一个线程运行一个子进程。尝试运行没有线程的子进程。另外,你指定了shell = True,所以它在shell中运行命令。所以有两个新进程,shell和命令。您还可以通过使shell = False来删除该shell。
+1
伟大的工作我的朋友,只需更改shell = False,并且result.terminate()将终止进程。谢谢。 – 2012-04-09 22:09:06
'ps'的输出是什么样的? – Keith 2012-04-09 20:41:14
@Keith:当我做ps aux | grep ping,它给出了ping进程运行,如果我不使用“kill”,它们总是在那里。 – 2012-04-09 20:43:13
它可能在那里,但它是什么状态?我想知道如果你不需要等待()这个子进程(这是一个僵尸进程)。 – Keith 2012-04-09 20:47:50