logo

Python - subprocess

Last Updated: 2024-01-20

To execute another program (e.g. a linux command), use subprocess

>>> import subprocess
>>> result = subprocess.run(["ls", "-l"])
(output of "ls -l")
>>> result
CompletedProcess(args=['ls', '-l'], returncode=0)

result is a CompletedProcess, however it does not capture the result; to do that add stdout

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