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 28n-rw-r--r-- 1 runner runner 5 Oct 16 20:15 filen-rw-r--r-- 1 runner runner 13 Oct 16 01:41 foo.txtn-rw-r--r-- 1 runner runner 102 Oct 17 01:58 main.pyn-rw-r--r-- 1 runner runner 4540 Oct 16 22:17 photo.jpgn-rw-r--r-- 1 runner runner 3449 Oct 16 22:24 poetry.lockndrwxr-xr-x 1 runner runner 36 Oct 15 23:31 __pycache__n-rw-r--r-- 1 runner runner 358 Oct 16 22:24 pyproject.tomln'
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.