Running shell command and capturing the 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:

import subprocess

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

Watch a course Python - The Practical Guide

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.

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.