How to execute a Program or System Command from Python

This article shows how to run a system command from Python and how to execute another program.

Use run commands

Use the subprocess module in the standard library:

import subprocess["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., *, 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 instead of .run():["ls", "-l"])

Another option is to use os.system():

import os os.system("ls -l")

This takes one single String as argument. However, 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."])

Similar to .run()it can take a lot of optional arguments which can be found here.

Warning: Using shell=True is discouraged

Both runand 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

🪁 Code faster with Kite, AI-powered autocomplete: Link *

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link *

* These are affiliate links. By clicking on it you will not have any additional costs, instead you will support me and my project. Thank you! 🙏

Check out my Courses