【发布时间】:2020-09-30 09:01:10
【问题描述】:
我在 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
有人知道这背后的原因吗?
附:我在 python3 中运行之前更改了 print 语句。
【问题讨论】:
-
我怀疑它在 Python 3 中使用
print语句完美运行。 -
我在运行之前更改了打印语句。
-
您的脚本在 python 2.7 (Linux) 中运行没有错误 - 但是在进程 p2 中超时到期并且您终止进程 p1 后,tcpdump 会抱怨。在 python 3.6 中,
write()给出了关于字节(不是 str)参数的错误。我会避免在这样的子进程中使用sudo(尽管它似乎在这里工作),因为当你操作标准输入/标准输出时密码输入是否会继续工作并不明显。
标签: python python-3.x python-2.7 multiprocessing devops