Skip to main content
 首页 » 编程设计

Python 子进程将输出作为 stderr 返回

2024年10月01日13cmt

我一直在研究与 ffmpeg 交互的 Python 脚本;然而,我注意到即使一切运行良好,stdout 还是空的并且 stderr 返回了我应该从 stdout 得到的结果。如何修复它以便输出将由 stdout 返回?

这是重现该现象的最简单示例:

from subprocess import Popen, PIPE 
 
p = Popen(['python', '-V'], stdin=PIPE, stdout=PIPE, stderr=PIPE) 
out, err = p.communicate() 
if out: 
    print("Output. ", out.decode()) 
else: 
    print("Error. ", err.decode()) 

这是输出:

Error.  Python 3.6.1 :: Anaconda 4.4.0 (64-bit) 

请注意,我使用的是 Windows 10。

请您参考如下方法:

您可以通过这样做将进程的 stderr 重定向到它的 stdout:

from subprocess import PIPE, STDOUT 
p = subprocess.Popen(["python", "-V"], stdout=PIPE, stderr=STDOUT) 

然后您可以像这样检索过程产生的输出:

out = p.stdout.read() 

这将在您的进程终止后返回标准输出的内容。