【发布时间】: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.16和3.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