W3docs

Running shell command and capturing the output

In Python, you can use the subprocess module to run shell commands and capture their output.

In Python, you can use the subprocess module to run shell commands and capture their output. Here's an example of how you can use the subprocess.run() function to run the 'ls' command and capture the output:

Running shell command and capturing the output in Python using the subprocess.run method

import subprocess

result = subprocess.run(['ls','-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = result.stdout.decode('utf-8')
print(output)

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

You can also use subprocess.check_output() which is a simpler version of run(), it returns the output as bytes and raises a CalledProcessError exception if the command returns a non-zero exit status.

Running shell command and capturing the output in Python using the subprocess.check_output method

import subprocess

output = subprocess.check_output(['ls','-l'])
print(output.decode('utf-8'))

In both cases, the output will be captured in the output variable, which you can then manipulate or print as desired.