从subprocess.run()
文档中的示例来看,似乎不应该有任何输出。
subprocess.run(["ls", "-l"]) # doesn't capture output
然而,在Python shell中尝试时,列表会被打印出来。我想知道这是否是默认行为以及如何抑制run()
的输出。
从subprocess.run()
文档中的示例来看,似乎不应该有任何输出。
subprocess.run(["ls", "-l"]) # doesn't capture output
然而,在Python shell中尝试时,列表会被打印出来。我想知道这是否是默认行为以及如何抑制run()
的输出。
以下是按照净化级别递减顺序的输出抑制方法。假设您使用的是Python 3。
subprocess.DEVNULL
。import subprocess
# To redirect stdout (only):
subprocess.run(
['ls', '-l'],
stdout = subprocess.DEVNULL
)
# to 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。
注意:下面的示例使用
universal_newlines=True
(Python <= 3.6)。
- 这将导致STDOUT和STDERR被捕获为
str
而不是bytes
。
- 省略
universal_newlines=True
以获取bytes
数据- Python >= 3.7接受
text=True
作为universal_newlines=True
的简写形式
capture_output=True
。import subprocess
result = subprocess.run(
['ls', '-l'],
capture_output = True, # Python >= 3.7 only
text = True # Python >= 3.7 only
)
print(result.stdout)
print(result.stderr)
import subprocess
result = subprocess.run(
['ls', '-l'],
stdout = subprocess.PIPE,
universal_newlines = True # Python >= 3.7 also accepts "text=True"
)
print(result.stdout)
# To also capture stderr...
result = subprocess.run(
['ls', '-l'],
stdout = subprocess.PIPE,
stderr = subprocess.PIPE,
universal_newlines = True # Python >= 3.7 also accepts "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,
universal_newlines = True # Python >= 3.7 also accepts "text=True"
)
print(result.stdout)
subprocess.DEVNULL
,因此可以直接分配stdout
参数而无需使用open
,只需使用stdout=subprocess.DEVNULL
。 - EquipDevdevnull
吗? - SethMMortonresult.stdout
。如果您想要实时捕获和打印输出,那么就会稍微复杂一些,因为您不能使用 subprocess.run
,而需要使用更底层的 subprocess.Popen
。当我需要这样做时,我通常会使用类似于这个答案的方法(请根据 Python 3 调整语法)。 - SethMMorton例如:捕获ls -a
命令的输出结果。
import subprocess
ls = subprocess.run(['ls', '-a'], capture_output=True, text=True).stdout.strip("\n")
print(ls)
subprocess.run()
默认不会捕获标准输出或标准错误,要想捕获它们需要将PIPE
传递给stdout
和/或stderr
参数(在链接的文档中有详细说明)。因此,除非你这样做,否则它们将像从其他进程一样正常显示。 - martineauprocess.call
)和Python 3.5(process.run
)之间的API发生了显着变化。我来到这里特意寻找Python 3的答案。这个问题的被接受的答案以及对它的顶级评论,在这种情况下比其他问题的答案更有用。 - GlennScapture_output=True
参数。 - Czechnology