如何从os.popen()获取stderr?

Dmi*_*ers 5 python python-2.7

如果我打电话

os.popen('foo').read()
Run Code Online (Sandbox Code Playgroud)

我想抓住

sh: foo: not found
Run Code Online (Sandbox Code Playgroud)

同样.
我没有该subprocess模块,因为这是嵌入式系统上的最小安装.

popen3,4也不起作用:

 File "/usr/lib/python2.7/os.py", line 667, in popen3
import subprocess
ImportError: No module named subprocess
Run Code Online (Sandbox Code Playgroud)

我想我能做到

os.popen(command + " 2>&1").read()
Run Code Online (Sandbox Code Playgroud)

管道它到stdout,但理想情况下我想分开得到它.

小智 3

由于应该使用 subprocess 代替 os.popen,因此您可以执行类似的操作

测试.py:

from subprocess import PIPE, Popen

p = Popen("foo", shell=True, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
print "stdout: '%s'" % stdout
print "stderr: '%s'" % stderr
Run Code Online (Sandbox Code Playgroud)

现在执行:

python test.py 
stdout: ''
stderr: '/bin/sh: 1: foo: not found
'
Run Code Online (Sandbox Code Playgroud)

注意 stderr 中的 CR。