【问题标题】:how do i test subprocess's stdout, stderr in python on windows我如何在 Windows 上的 python 中测试子进程的 stdout、stderr
【发布时间】:2015-06-20 12:00:30
【问题描述】:
>>> 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 的标准输出或标准错误以测试它们的一些特性(不是当前的sys.__stdout__)。如何从 python 解释器执行此操作?

【问题讨论】:

  • 你想要输出到文件还是到 python shell?
  • 我可以在任何地方获得对 std 对象的引用!只是想尝试这个对象,到目前为止它只是一个 None ref...

标签: python subprocess stdout


【解决方案1】:

我想你在找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] 

是标准错误

【讨论】:

  • 你不需要 shell=True
  • @PadraicCunningham 我从他们那里复制了这个问题:p
  • 实际上刚刚看到 OP 正在使用 windows,所以它需要 shell=True 并且只需传递字符串 dir 或使用["cmd", "/c", "dir"],在 linux 上使用 shell=True 和 args 列表将无法正常工作
【解决方案2】:

您可以使用 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)

【讨论】:

  • 在 Windows 上添加 shell=Truedir 是内部命令)并将命令作为字符串而不是列表传递。要获得子进程的输出,请使用e.output,而不是e.message。后者也包括其他信息。
猜你喜欢
  • 2011-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-21
  • 1970-01-01
  • 1970-01-01
  • 2012-03-16
相关资源
最近更新 更多