如何抑制或捕获 subprocess.run() 的输出? [英] How to suppress or capture the output of subprocess.run()?
问题描述
来自 subprocess.run() 文档中的示例
似乎不应该有任何输出
From the examples in docs on subprocess.run()
it seems like there shouldn't be any output from
subprocess.run(["ls", "-l"]) # doesn't capture output
但是,当我在 python shell 中尝试它时,列表会被打印出来.我想知道这是否是默认行为以及如何抑制 run()
的输出.
However, when I try it in a python shell the listing gets printed. I wonder if this is the default behaviour and how to suppress the output of run()
.
推荐答案
这里是如何抑制输出,按照清洁度递减的顺序.他们假设您使用的是 Python 3.
Here is how to suppress output, in order of decreasing levels of cleanliness. They assume you are on 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 相同.
- If you want a fully manual method, can redirect to
/dev/null
by opening the file handle yourself. Everything else would be identical to method #1.
import os
import subprocess
with open(os.devnull, 'w') as devnull:
subprocess.run(['ls', '-l'], stdout=devnull)
这里是如何捕获输出(以供以后使用或解析),按清洁度级别递减的顺序排列.他们假设您使用的是 Python 3.
Here is how to capture output (to use later or parse), in order of decreasing levels of cleanliness. They assume you are on Python 3.
- 如果您只想独立捕获 STDOUT 和 STDERR,并且您使用的是 Python >= 3.7,请使用
capture_output=True
.
import subprocess
result = subprocess.run(['ls', '-l'], capture_output=True)
print(result.stdout)
print(result.stderr)
- 您可以使用
subprocess.PIPE
独立捕获 STDOUT 和 STDERR.这确实适用于 Python 版本 <3.7,例如 Python 3.6.
- You can use
subprocess.PIPE
to capture STDOUT and STDERR independently. This does work on Python versions < 3.7, such as Python 3.6.
import subprocess
result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
print(result.stdout)
# To also capture stderr...
result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
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)
print(result.stdout)
注意:默认情况下,捕获的输出以bytes
形式返回.如果您想捕获为文本(例如 str
),请使用 universal_newlines=True
(或在 Python >=3.7 上,使用无限更清晰易懂的选项 text=True
- 它与 universal_newlines
相同,但名称不同.
NOTE: By default, captured output is returned as bytes
. If you want to capture as text (e.g. str
), use universal_newlines=True
(or on Python >=3.7, use the infinitely more clear and easy-to-understand option text=True
- it's the same a universal_newlines
but with a different name).
这篇关于如何抑制或捕获 subprocess.run() 的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!