![](/img/trans.png)
[英]Python - [Subprocess Popen Communicate] hangs on execution
[英]Python subprocess communicate hangs
我知道这是一个经常被问到的问题,我已经尝试了可以在这里和其他站点上找到的任何解决方案,但不能解决我的问题。 我的困境如下(在Windows上):
我有一个主脚本(main.py),在其中通过Popen调用另一个脚本(sniffer.py)创建一个子进程。 之后,我要在main.py中做一些事情,最后要向该子进程发送一个字符,以完成sniffer.py中的无限循环,最后完成整个子进程。
main.py
process = Popen(["python", "sniffer.py", receiverIP, senderIP, "udp", path],stdin=PIPE)
#do some stuff
process.communicate('terminate')
嗅探器
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结合使用,但没有效果。
注意:我注意到,在我的communication()调用之后,sniffer.py中的while循环不会继续(整个脚本只是挂起)
与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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.