Python 2.7 和 3.8 之间的子进程或线程差异

subprocess or threading differences between Python 2.7 and 3.8

我正在使用以下代码执行子流程(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

事实证明,版本之间的文件 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