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)
小智 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)
| 归档时间: |
|
| 查看次数: |
20723 次 |
| 最近记录: |