HOWTO · Python
How to Run Bash Command in Python
This tutorial demonstrates how to run bash commands in Python, focusing on Git commands. Learn the best methods, including subprocess and os.system, to execute commands effectively. Enhance your workflow with practical examples and clear explanations. Perfect for developers looking to automate tasks and streamline their processes.
On this page
Python can start command-line programs and shell commands for tasks such as creating directories or using Git. For commands that finish, subprocess.run() is usually the best starting point: it can capture output and errors and provides a return code. Use os.system() for simple cases that do not need captured output, and choose subprocess.Popen() when you need to interact with a process while it runs.
Run a command with subprocess.run()
Pass a sequence of arguments to invoke an executable directly. This avoids asking a shell to parse the command. The example uses the running Python interpreter, so it does not depend on Git being installed or on a particular shell.
import subprocess
import sys
result = subprocess.run(
[sys.executable, "-c", "print('Hello from Python')"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
print("stdout:", result.stdout)
print("stderr:", result.stderr)
print("return code:", result.returncode)
stdout: b'Hello from Python\n'
stderr: b''
return code: 0
stdout and stderr are bytes here, and returncode is an integer. A return code of 0 conventionally indicates success; a nonzero value signals that the program reported a problem. You can check it yourself or pass check=True to have run() raise CalledProcessError for a nonzero return code. To run Git, for example, pass an argument list such as ['git', 'status']; its output depends on the repository and should be handled as data, not assumed to have fixed contents.
A program invocation is not automatically a Bash command. Shell syntax such as pipes, redirects, or && requires a shell. Setting shell=True asks Python to use the platform shell; it does not guarantee Bash. Avoid interpolating untrusted input into a shell command because it can enable command injection.
Run a shell command with os.system()
os.system() is a limited option for a simple command when you do not need to capture its output or handle errors in detail. For example, os.system("mkdir reports") asks the platform shell to run the directory-creation command. The command writes to the inherited console streams. The function returns a status value, not the command’s ordinary output; interpreting that status can vary by platform. Prefer subprocess.run() when you need to inspect captured output, errors, or a return code consistently.
Use subprocess.Popen() for ongoing processes
Use subprocess.Popen() when the program needs input or other interaction before it finishes. It starts the process and gives your code a process object to work with. For a process with bounded output, set stdout=subprocess.PIPE and stderr=subprocess.PIPE, then call communicate() to read those streams and wait for completion. The returned stream values are bytes unless you arrange decoding separately.
communicate() is useful when the process will finish and its captured output can fit in memory. It is not a streaming approach for unbounded output. Once communicate() has completed, the process has finished; there is no need to call kill() or terminate() on it. For ordinary commands that simply finish, run() provides the simpler interface.
Choose the right method
Use subprocess.run() for most commands: pass an argument list, capture streams when needed, and inspect returncode. Use os.system() only when a short shell command is enough and its output and detailed status are unimportant. Use Popen() when your program must manage a running process or exchange data with it. Choose a shell only when the command needs shell syntax, and keep untrusted values out of interpolated shell strings.