How to execute a Program or System Command from Python
Learn how to run a system command from Python and how to execute another program.
This article shows how to run a system command from Python and how to execute another program.
#more
Use subprocess.run()
to run commands¶
Use the subprocess module in the standard library:
import subprocess
subprocess.run(["ls", "-l"])
It runs the command described by args. Note that args must be a List of Strings, and not one single String with the whole command. The run
function can take various optional arguments. More information can be found here.
subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None, **other_popen_kwargs)
¶
Note: In Python 3.4 and earlier, use subprocess.call()
instead of .run()
:
subprocess.call(["ls", "-l"])
Another option is to use os.system()
:
import os
os.system("ls -l")
subprocess.run()
is more powerful and more flexibel and even the official documentation recommends to use it over os.system()
. Use subprocess.Popen()
to execute programs¶
To execute a child program in a new process, use subprocess.Popen()
:
import subprocess
subprocess.Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
.run()
it can take a lot of optional arguments which can be found here. Warning: Using shell=True
is discouraged¶
Both run
and Popen
can take the keyword argument shell. If shell is True, the specified command will be executed through the shell. However, using this is strongly discouraged for security reasons! More information can be found here.
FREE VS Code / PyCharm Extensions I Use
✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*
Python Problem-Solving Bootcamp
🚀 Solve 42 programming puzzles over the course of 21 days: Link*