【问题标题】:python2 and python3 multiprocessing errorpython2和python3多处理错误
【发布时间】: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


【解决方案1】:

您需要在离开程序之前终止进程并从子进程中删除 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 运行这个脚本,一切都会好起来的。

【讨论】:

    猜你喜欢
    • 2017-04-26
    • 1970-01-01
    • 2017-06-20
    • 1970-01-01
    • 2019-06-06
    • 2023-04-10
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    相关资源
    最近更新 更多