从subprocess.run()
上的文档中的示例看来,
subprocess.run(["ls", "-l"]) # doesn't capture output
然而,当我在python shell中尝试它时,列表被打印出来。我想知道这是否是默认行为以及如何抑制run()
的输出。
答案 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)