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.
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
Another option is to use
import os os.system("ls -l")
subprocess.run()is more powerful and more flexibel and even the official documentation recommends to use it over
subprocess.Popen()to execute programs¶
To execute a child program in a new process, use
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.
shell=True is discouraged¶
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** This is an affiliate link. By clicking on it you will not have any additional costs. Instead, you will support my project. Thank you! 🙏