Categories
Python Answers

How to run a shell command and capturing the output with Python?

Spread the love

Sometimes, we want to run a shell command and capturing the output with Python.

In this article, we’ll look at how to run a shell command and capturing the output with Python.

How to run a shell command and capturing the output with Python?

To run a shell command and capturing the output with Python, we can use the subprocess.run method.

For instance, we write:

import subprocess

result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
print(result.stdout)

We call subprocess.run with an array that has the command string with its arguments.

And we set stdout to subprocess.PIPE to pipe the input to stdout.

We then get the output from the result.stdout property as a binary string.

As a result, we get something like:

b'total 28\n-rw-r--r-- 1 runner runner    5 Oct 16 20:15 file\n-rw-r--r-- 1 runner runner   13 Oct 16 01:41 foo.txt\n-rw-r--r-- 1 runner runner  102 Oct 17 01:58 main.py\n-rw-r--r-- 1 runner runner 4540 Oct 16 22:17 photo.jpg\n-rw-r--r-- 1 runner runner 3449 Oct 16 22:24 poetry.lock\ndrwxr-xr-x 1 runner runner   36 Oct 15 23:31 __pycache__\n-rw-r--r-- 1 runner runner  358 Oct 16 22:24 pyproject.toml\n'

as the value of result.stdout.

Conclusion

To run a shell command and capturing the output with Python, we can use the subprocess.run method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *