如何仅使用fork/exec/pipe/dup2捕获子进程的stdout



所以我试图只使用fork/exec/pipe/dup2捕获子进程的输出,但输出一直打印到终端。这是我现在的代码:

import os
import sys
pipeIn, pipeOut = os.pipe()
processid = os.fork()
if processid == 0:
try:
os.close(pipeIn)
os.dup2(pipeOut, 0)
os.execv(sys.executable, [sys.executable, 'helloWorld.py'])
sys.exit(0)
except FileNotFoundError:
print("ERROR: File not found.")
sys.exit(1)
elif processid == -1:
print("ERROR: Child was unable to run.")
sys.exit(1)
else:
wait = os.wait()
if wait[1] == 0:
os.close(pipeOut)
output = os.read(pipeIn, 100)
else:
output = "ERROR"

有人能告诉我出了什么问题吗?以及如何捕获exec命令的输出,而不是将其打印到终端。(也不允许使用临时文件(。

标准输出是FD 1,但您的管道是dup'而不是FD 0(标准输入(。将os.dup2(pipeOut, 0)更改为os.dup2(pipeOut, 1)

最新更新