首先是蟒蛇子流程模块是正确的答案。
作为子流程示例:
import subprocess
x = subprocess.check_output(["echo","one","two","three"])
其中 x 将是输出(python3 字节类:x.decode('utf-8')
对于字符串)
请注意,这不会重复 stderr。如果您还需要 stderr,您可以执行以下操作:
x = subprocess.check_output(["bash","-c", 'echo foo; echo bar >&2'],stderr=subprocess.STDOUT)
当然,还有许多其他方法来捕获 stderr,包括捕获到不同的输出变量。
使用直接控制
但是,如果您正在做一些棘手的事情并且需要直接控制,请检查下面的代码:
import os
rside, wside = os.pipe()
if not os.fork():
# Child
os.close(rside)
# Make stdout go to parent
os.dup2(wside, 1)
# Make stderr go to parent
os.dup2(wside, 2)
# Optionally make stdin come from nowhere
devnull = os.open("/dev/null", os.O_RDONLY)
os.dup2(devnull, 0)
# Execute the desired program
os.execve("/bin/bash",["/bin/bash","-c","echo stdout; echo stderr >&2"],os.environ)
print("Failed to exec program!")
sys.exit(1)
# Parent
os.close(wside)
pyrside = os.fdopen(rside)
for line in pyrside:
print("Child (stdout or stderr) said: <%s>"%line)
# Prevent zombies! Reap the child after exit
pid, status = os.waitpid(-1, 0)
print("Child exited: pid %d returned %d"%(pid,status))
Note: @初学者的回答在几个方面存在缺陷:包含了 os._exit(0) ,它立即导致子进程退出,使其他一切变得毫无意义。没有 os.execve() 使得问题的主要目标毫无意义。无法访问孩子的标准输出/标准错误作为另一个问题目标。