如何测试子流程';windows上python中的stdout、stderr
我想检索如何测试子流程';windows上python中的stdout、stderr,python,subprocess,stdout,Python,Subprocess,Stdout,我想检索子流程的stdout或stderr来测试它们的一些特性(而不是当前的系统。如何从python解释器中执行此操作?我想您正在寻找 示例 >>> import subprocess >>> f = open('txt', 'w+') >>> p = subprocess.Popen(['dir'],stdout=f,stderr=f, shell=True) >>> p.communicate() (None, None
子流程的stdout或stderr来测试它们的一些特性(而不是当前的系统。如何从python解释器中执行此操作?我想您正在寻找
示例
>>> 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)
可以看出,
>>> from subprocess import Popen, PIPE
>>> process = subprocess.Popen(['ls'], stdout = PIPE, stderr = PIPE, shell = True )
>>> process.communicate()
('file\nfile1\nfile2, '')
是命令的标准输出,并且
process.communicate()[0]
是stderr您可以使用check_输出并捕获调用的进程错误:
process.communicate()[1]
您希望输出到文件还是pythonshell?我可以在任何地方获得对std对象的引用!只是想用这个对象进行实验,到目前为止,它只是一个无引用的对象……你不需要shell=True@PadraicCunningham我从他们那里复制了这个问题:实际上,我刚刚看到OP正在使用windows,所以它需要shell=True,只需传递字符串dir或使用[“cmd”,“/c”,“dir”]
,在linux上使用shell=True和参数列表将无法正常工作在Windows上添加shell=True
(dir
是一个内部命令),并将命令作为字符串而不是列表传递。要获取子流程的输出,请使用e.output
,而不是e.message
。后者还包括其他信息。
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)