
[英]Capture the output of subprocess.run() but also print it in real time?
[英]How to suppress or capture the output of subprocess.run()?
从 subprocess.run subprocess.run()
文档中的示例来看,似乎不应该有任何 output 来自
subprocess.run(["ls", "-l"]) # doesn't capture output
但是,当我在 python shell 中尝试时,清单会打印出来。 我想知道这是否是默认行为以及如何抑制run()
的 output。
以下是如何抑制输出,按清洁度降低的顺序排列。 他们假设您使用的是 Python 3。
subprocess.DEVNULL
目标。import subprocess
subprocess.run(['ls', '-l'], stdout=subprocess.DEVNULL)
# The above only redirects stdout...
# this will also redirect stderr to /dev/null as well
subprocess.run(['ls', '-l'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# Alternatively, you can merge stderr and stdout streams and redirect
# the one stream to /dev/null
subprocess.run(['ls', '-l'], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
/dev/null
。 其他一切都与方法#1 相同。import os
import subprocess
with open(os.devnull, 'w') as devnull:
subprocess.run(['ls', '-l'], stdout=devnull)
以下是如何捕获输出(以供以后使用或解析),按清洁度递减的顺序排列。 他们假设您使用的是 Python 3。
注意:以下示例使用
text=True
。
- 这会导致 STDOUT 和 STDERR 被捕获为
str
而不是bytes
。
- 省略
text=True
以获取bytes
数据text=True
仅适用于 Python >= 3.7,在 Python <= 3.6 上使用universal_newlines=True
universal_newlines=True
与text=True
相同,但输入更冗长,但应存在于所有 Python 版本中
capture_output=True
。import subprocess
result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
print(result.stdout)
print(result.stderr)
subprocess.PIPE
独立捕获 STDOUT 和 STDERR。 这适用于支持subprocess.run
的任何Python 版本。import subprocess
result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE, text=True)
print(result.stdout)
# To also capture stderr...
result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
print(result.stdout)
print(result.stderr)
# To mix stdout and stderr into a single string
result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
print(result.stdout)
例如:捕获ls -a
的输出
import subprocess
ls = subprocess.run(['ls', '-a'], capture_output=True, text=True).stdout.strip("\n")
print(ls)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.