我知道这是一个常见问题,我已经尝试了在这里和其他网站上可以找到的任何解决方案^但无法解决我的问题。 我的困境如下(在 Windows 上):
我有一个主脚本(main.py),我通过 Popen 调用另一个脚本(sniffer.py)创建一个子进程。之后我在 main.py 中做了一些事情,最后想向子进程发送一个字符来完成 sniffer.py 中的无限循环,最后完成整个子进程。
主.py
process = Popen(["python", "sniffer.py", receiverIP, senderIP, "udp", path],stdin=PIPE)
#do some stuff
process.communicate('terminate')
嗅探器.py
def check(done):
while True:
if sys.stdin.read() == 'terminate':
done = True
break
def sniff(someparams):
done = False
input_thread = threading.Thread(target=check, args=(done,))
input_thread.daemon = True
input_thread.start()
while True:
#do some stuff
if done:
break
我也尝试将通信调用与 stdin.write 结合起来,但没有效果。
注意:我注意到,sniffer.py 中的 while 循环在我的 communications() 调用之后不会继续(整个脚本只是挂起)
与
subprocess
无关。
您在本地将
done
更改为 True
。您必须全局定义它才能使最后一个循环正确退出。
done = False
def check():
global done
while True:
if sys.stdin.read() == 'terminate':
done = True
break
def sniff(someparams):
global done
done = False
input_thread = threading.Thread(target=check)
input_thread.daemon = True
input_thread.start()
while True:
#do some stuff
if done:
break