如何抑制或捕获subprocess.run()的输出?

2024-06-13 17:06:28 发布

您现在位置:Python中文网/ 问答频道 /正文

^{}文档中的示例来看,似乎不应该有来自

subprocess.run(["ls", "-l"])  # doesn't capture output

但是,当我在一个python shell中尝试时,会打印出清单。我想知道这是否是默认行为,以及如何抑制run()的输出。


Tags: run文档示例outputshelllscapturesubprocess
1条回答
网友
1楼 · 发布于 2024-06-13 17:06:28

下面是如何抑制输出,以降低清洁度。他们假设你在Python 3上。

  1. 您可以重定向到特殊的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)
  1. 如果您想要一个完全手动的方法,可以通过自己打开文件句柄重定向到/dev/null。其他一切都将与方法1相同。
import os
import subprocess

with open(os.devnull, 'w') as devnull:
    subprocess.run(['ls', '-l'], stdout=devnull)

下面是如何捕获输出(稍后使用或解析),以降低清洁度级别。他们假设你在Python 3上。

  1. 如果您只想独立捕获STDOUT和STDERR,并且您使用的是Python>;=3.7,请使用capture_output=True
import subprocess

result = subprocess.run(['ls', '-l'], capture_output=True)
print(result.stdout)
print(result.stderr)
  1. 您可以使用subprocess.PIPE独立捕获STDOUT和STDERR。
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相同,但名称不同)。

相关问题 更多 >