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 function to run the 'ls' command and capture the output:

import subprocess

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

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'])

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