[英]python2 and python3 multiprocessing error
我在 python2 和 python3 环境中运行以下脚本。
import subprocess as sub
import sys
#import time
import multiprocessing, time, signal
def tcpdump():
p = sub.Popen(('sudo', 'tcpdump', '-l', '-xx'), stdout=sub.PIPE)
for row in iter(p.stdout.readline, b''):
sys.stdout.write(row.rstrip())
def print_hello():
print "yo"
time.sleep(20)
print "goodbye"
def main():
p1 = multiprocessing.Process(target=tcpdump)
p2 = multiprocessing.Process(target=print_hello)
p1.start()
p2.start()
while p2.is_alive():
time.sleep(2)
p1.terminate()
print "We terminated"
#p1.terminate()
#print "one more time"
#print_hello()
#tcpdump()
main()
在 python3 中,它运行完美,但在 python2 中,它给了我一个错误
tcpdump: Unable to write output: Broken pipe
有人可以知道这背后的原因吗?
PS我在python3中运行之前更改了打印语句。
您需要在离开程序之前终止该进程并从子进程中删除 sudo。 这段代码在我的机器上工作:
import subprocess as sub
import sys
#import time
import multiprocessing, time, signal
def tcpdump(p):
for row in iter(p.stdout.readline, b''):
sys.stdout.write(row.rstrip())
def print_hello():
print "yo"
time.sleep(5)
print "goodbye"
def main():
p = sub.Popen(('tcpdump', '-l', '-xx'), stdout=sub.PIPE)
p1 = multiprocessing.Process(target=tcpdump, args=(p,))
p2 = multiprocessing.Process(target=print_hello)
p1.start()
p2.start()
while p2.is_alive():
time.sleep(2)
p1.terminate()
p.kill()
print "We terminated"
#p1.terminate()
#print "one more time"
#print_hello()
#tcpdump()
main()
使用 sudo 运行这个脚本,一切都应该没问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.