>>> import subprocess
>>> f = open('txt', 'w+')
>>> p = subprocess.Popen(['dir'],stdout=f,stderr=f, shell=True)
>>> p.communicate()
(None, None) # stdout, stderr are empty. Same happens if I open a win32 gui app instead of python (don't think win32 gui apps set a stdout/stderr)
我想检索subprocess
的stdout或stderr来测试它们的一些特征(不是当前的sys.__stdout__
)。我怎么能从python解释器那里做到这一点?
答案 0 :(得分:2)
我认为您正在寻找subprocess.PIPE
示例强>
>>> from subprocess import Popen, PIPE
>>> process = subprocess.Popen(['ls'], stdout = PIPE, stderr = PIPE, shell = True )
>>> process.communicate()
('file\nfile1\nfile2, '')
可以看出,
process.communicate()[0]
是命令的标准输出和
process.communicate()[1]
是stderr
答案 1 :(得分:1)
您可以使用check_output并捕获CalledProcessError:
from subprocess import check_output, CalledProcessError
try:
out = check_output(["dir"]) # windows out = check_output(["cmd", "/c", "dir"])
except CalledProcessError as e:
out = e.output
print(out)