如何抑制或捕获 subprocess.run() 的输出?
- 2025-04-15 09:19:00
- admin 原创
- 27
问题描述:
从文档中的示例来看,subprocess.run()
似乎不应该有任何输出
subprocess.run(["ls", "-l"]) # doesn't capture output
但是,当我在 Python Shell 中尝试时,列表会被打印出来。我想知道这是否是默认行为,以及如何抑制 的输出run()
。
解决方案 1:
压制
以下是按清洁度递减的顺序抑制输出的方法。假设您使用的是 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
如果您只是想独立捕获 STDOUT 和 STDERR,并且您使用的是 Python >= 3.7,请使用
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)
您可以使用
subprocess.PIPE
分别捕获 STDOUT 和 STDERR。此功能适用于任何支持 的 Python 版本subprocess.run
。
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)
解决方案 2:
例如:捕获输出ls -a
import subprocess
ls = subprocess.run(['ls', '-a'], capture_output=True, text=True).stdout.strip("
")
print(ls)
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD