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

pla*_*etp 22 python subprocess python-3.x

从文档中的示例subprocess.run()来看,似乎不应该有任何输出

subprocess.run(["ls", "-l"])  # doesn't capture output
Run Code Online (Sandbox Code Playgroud)

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

Set*_*ton 55

禁止输出,可以重定向到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)
Run Code Online (Sandbox Code Playgroud)

如果要捕获输出(以后使用或解析),则需要使用/dev/null

import os
import subprocess

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

  • 请注意,从Python ver.3.3实际上有一个`subprocess.DEVNULL`,所以`stdout`参数可以在没有`open`的情况下直接分配,只需使用`stdout = subprocess.DEVNULL`. (25认同)
  • @Sabrina 你定义了“devnull”吗? (2认同)

小智 9

例如:捕获输出 ls -a

import subprocess
ls = subprocess.run(['ls', '-a'], capture_output=True, text=True).stdout.strip("\n")
print(ls)
Run Code Online (Sandbox Code Playgroud)

  • 这适用于 python 3.7,但不适用于 python 3.6(我得到 `TypeError: __init__() got an Unexpected keywords argument 'capture_output'`) (7认同)