我需要启动一个子进程并启用两个线程来读取其 stdout
和stderr
分别。
下面的代码只是考虑stdout
:
def reader(rfd):
while True:
try:
data = os.read(rfd, bufsize)
except OSError:
break
else:
chomp(data)
rout, wout = os.pipe()
tout = threading.Thread(target=reader, args=(rout,))
tout.start()
subprocess.check_call(command, bufsize=bufsize, stdout=wout, stderr=werr)
os.close(wout)
os.close(rout)
tout.join()
该代码有效,但我注意到并非所有数据都被处理,就像 os.close(wout)
一样。函数在读取所有数据之前杀死读取器。另一方面,如果我不关闭wout
我的进程将永远卡在tout.join()
上.
我可以看出这是一个缓冲问题,因为如果我输入一个非常糟糕的time.sleep(0.1)
就在subprocess.check_call(...)
之后一切都神奇地起作用。
最好的方法是刷新而不是等待,但是任何对 os.fsync()
的调用通过管道给出 OSError: [Errno 22] Invalid argument
.
有关如何刷新使用 os.pipe
创建的管道的任何提示?
最佳答案
我建议使用 Popen
而不是 os.pipe
进行进程间通信。
例如。
writer_process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
reader_thread = threading.Thread(target=reader, args=(writer_process.stdout,))
reader_thread.start()
reader_thread.join()
但是,如果您确实想使用os.pipe
,那么您将更容易将它们视为文件对象。 Python 内置的文件上下文管理器将确保文件正确刷新和关闭。
例如。
def reader(fd):
with os.fdopen(fd, bufsize=bufsize) as f:
while True:
data = f.read(bufsize)
if not data:
break
chomp(data)
和
with os.fdopen(wout, "w", bufsize=bufsize) as f:
subprocess.check_call(cmd, stdout=f)
关于python - 关闭前冲洗管道 (os.pipe),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25866092/