To capture the output of the subprocess. run method, use an additional argument named “capture_output=True”. You can individually access stdout and stderr values by using “output. stdout” and “output.
To hide output of subprocess with Python, we can set stdout to subprocess. DEVNULL`. to output the echo command's output to dev null by setting the stdout to subprocess. DEVNULL when we call subprocess.
subprocess. check_output() is the one that runs the command and returns the return value. If you want the output write your value to STDOUT and use check_output() to get the value.
Here is how to suppress output, in order of decreasing levels of cleanliness. They assume you are on Python 3.
subprocess.DEVNULL
target.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)
/dev/null
by opening the file handle yourself. Everything else would be identical to method #1.import os
import subprocess
with open(os.devnull, 'w') as devnull:
subprocess.run(['ls', '-l'], stdout=devnull)
Here is how to capture output (to use later or parse), in order of decreasing levels of cleanliness. They assume you are on Python 3. The below examples use text=True
(Python >= 3.7 only, use universal_newlines=True
on Python <= 3.6 which is identical but more verbose to type) to return the output as str
instead of bytes
- omit text=True
/universal_newlines=True
to get bytes
data.
capture_output=True
.import subprocess
result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
print(result.stdout)
print(result.stderr)
subprocess.PIPE
to capture STDOUT and STDERR independently. This works on any version of Python that supports subprocess.run
.import subprocess
result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE, universal_newlines=True)
print(result.stdout)
# To also capture stderr...
result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
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, universal_newlines=True)
print(result.stdout)
ex: to capture the output of ls -a
import subprocess
ls = subprocess.run(['ls', '-a'], capture_output=True, text=True).stdout.strip("\n")
print(ls)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With