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)
import subprocess
result = subprocess.run(['ls', '-l'], capture_output=True)
print(result.stdout)
print(result.stderr)
您可以使用subprocess.PIPE独立捕获STDOUT和STDERR。
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)
下面是如何抑制输出,以降低清洁度。他们假设你在Python 3上。
subprocess.DEVNULL
目标。/dev/null
。其他一切都将与方法1相同。下面是如何捕获输出(稍后使用或解析),以降低清洁度级别。他们假设你在Python 3上。
capture_output=True
。subprocess.PIPE
独立捕获STDOUT和STDERR。注意:默认情况下,捕获的输出返回为
bytes
。如果要捕获为文本(例如str
),请使用universal_newlines=True
(或者在Python>;=3.7上,使用更加清晰易懂的选项text=True
-它与universal_newlines
相同,但名称不同)。相关问题 更多 >
编程相关推荐