【问题标题】:subprocess or threading differences between Python 2.7 and 3.8Python 2.7 和 3.8 之间的子进程或线程差异
【发布时间】:2021-05-11 07:51:31
【问题描述】:

我正在使用以下代码来执行子进程(Python 3 脚本)。使用 Python 3 运行时,代码会正确读取子进程的输出。使用 Python 2.7 运行时,我没有得到任何输出。这个脚本只是一个测试脚本,我需要从一个更大的 Python 2.7 应用程序中实际运行子进程,所以我不能只使用 Python3。

# client.py:  test client for communicating with the wrapper

from subprocess import Popen, PIPE
from threading import Thread
from time import sleep

def read_it():
    print(u"read_it thread running")
    while True:
    
        for msg in process.stdout:
            print(u"subprocess output: {}".format(msg.rstrip()))
        

print(u"subprocess starting")
process = Popen(['/usr/bin/python3', './wrapper.py', 'arg1', 'arg2'], 
                                stdin=PIPE, stdout=PIPE, close_fds=True, bufsize=1, universal_newlines=True)
print(u"subprocess running: {}".format(process.pid))
                                
thread = Thread(target=read_it)
thread.daemon = True
thread.start()

sleep(5.0)  # wait for initial output from subprocess

【问题讨论】:

  • 你的代码使用2.7.163.8.2对我来说很好。
  • @MauriceMeyer 你是如何在没有 wrapper.py 的情况下测试它的?
  • @Flyingdiver:我用过:import time; for x in range(10): print(x, time.time())
  • 嗯。我正在使用 sys.stdout.write,而不是打印。让我试试看。
  • 不,使用 Python 2 仍然没有输出,并且 Python3 中的管道错误。

标签: python python-3.x multithreading python-2.7 subprocess


【解决方案1】:

事实证明,版本之间的文件 io 缓冲是问题所在。但这适用于两个 Python 版本:

# client.py:  test client for communicating with the wrapper

from subprocess import Popen, PIPE
from threading import Thread
from time import sleep

def read_it():
    print(u"read_it thread running")
    while True:
    
        msg = process.stdout.readline()
        print(u"subprocess output: {}".format(msg.rstrip()))
        

print(u"subprocess starting")
process = Popen(['/usr/bin/python3', './wrapper.py', 'arg1', 'arg2'], 
                                stdin=PIPE, stdout=PIPE, close_fds=True, bufsize=1, universal_newlines=True)
print(u"subprocess running: {}".format(process.pid))
                                
thread = Thread(target=read_it)
thread.daemon = True
thread.start()

sleep(5.0)  # wait for initial output from subprocess

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-08
    • 1970-01-01
    • 2017-05-30
    • 2016-12-03
    相关资源
    最近更新 更多