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

时间:2016-12-15 19:21:11

标签: python python-3.x subprocess

subprocess.run()上的文档中的示例看来,

似乎不应该有任何输出
subprocess.run(["ls", "-l"])  # doesn't capture output

然而,当我在python shell中尝试它时,列表被打印出来。我想知道这是否是默认行为以及如何抑制run()的输出。

2 个答案:

答案 0 :(得分:41)

取消输出,您可以重定向到/dev/null

import os
import subprocess

with open(os.devnull, 'w') as devnull:
    subprocess.run(['ls', '-l'], stdout=devnull)
    # The above only redirects stdout...
    # this will also redirect stderr to /dev/null as well
    subprocess.run(['ls', '-l'], stdout=devnull, stderr=devnull)
    # Alternatively, you can merge stderr and stdout streams and redirect
    # the one stream to /dev/null
    subprocess.run(['ls', '-l'], stdout=devnull, stderr=subprocess.STDOUT)

如果您想捕获输出(以后使用或解析),您需要使用subprocess.PIPE

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)

答案 1 :(得分:1)

ex:捕获ls -a

的输出
import subprocess
ls = subprocess.run(['ls', '-a'], capture_output=True, text=True).stdout.strip("\n")
print(ls)