![](/img/trans.png)
[英]Gently kill a process created with Python's subprocess.Popen() in Windows
[英]python Popen: How do I stop(kill) the subprocess that created using Popen?
得到結果后,我需要停止我在python通過Popen發出的服務(在另一個線程的后台運行),但是下面的方法失敗了(只是為了解釋而使用ping
):
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 for ping
時,它仍然存在。 如何殺死Popen打開的子進程? 謝謝。
PS:我也試過result.terminate(),也沒有真正解決問題。
您實際上不需要從線程運行子進程。 嘗試在沒有線程的情況下運行子進程。 此外,您指定了 shell=True,因此它在 shell 中運行命令。因此有兩個新進程,即 shell 和命令。 您還可以通過設置 shell=False 來刪除 shell。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.