Python offers several ways to run system commands. For Python 3, prefer
subprocess.run(): it can capture output, check the exit status, and enforce a timeout.The
ls and shell pipeline examples below are intended for Linux and macOS. On Windows, substitute suitable commands.Run a command
Pass the executable and its arguments as a list. By default, the child inherits standard output and standard error, so its output appears in the terminal.
python_snippet
Python · 4 lines|
| import subprocess |
| result = subprocess.run(["ls", "-l"]) |
| print("Exit code:", result.returncode) |
This starts
ls directly without a shell. An exit code of zero normally indicates success; a nonzero code indicates failure.Capture output and handle errors
Use
capture_output=True to capture both output streams and text=True to decode them into strings. With check=True, a nonzero exit code raises CalledProcessError.python_snippet
Python · 18 lines|
| import subprocess |
| try: |
| result = subprocess.run( |
| ["ls", "-l"], |
| capture_output=True, |
| text=True, |
| check=True, |
| timeout=10, |
| ) |
| print(result.stdout) |
| except subprocess.CalledProcessError as exc: |
| print(f"Command failed with exit code {exc.returncode}") |
| print(exc.stderr) |
| except subprocess.TimeoutExpired: |
| print("Command timed out") |
| except FileNotFoundError: |
| print("Executable not found") |
Without
check=True, inspect result.returncode yourself. The timeout is in seconds; if it expires, run() kills and waits for the child before raising TimeoutExpired.When to use a shell
A shell interprets syntax such as pipes, redirection, glob expansion, and shell built-ins. Enable it explicitly when you need that syntax:
python_snippet
Python · 10 lines|
| import subprocess |
| result = subprocess.run( |
| "printf 'hello\\nworld\\n' | grep hello", |
| shell=True, |
| capture_output=True, |
| text=True, |
| check=True, |
| ) |
| print(result.stdout) |
Security: Never concatenate untrusted input into a shell command string: it can result in command injection. Prefer a list of arguments and the default
shell=False when launching a program directly. A list does not interpret shell syntax, and finding an executable through PATH alone does not require shell=True.Control a process with Popen
For more control over the child process, use
Popen. The following example waits for the process and reads both pipes with communicate():python_snippet
Python · 15 lines|
| import subprocess |
| process = subprocess.Popen( |
| ["ls", "-l"], |
| stdout=subprocess.PIPE, |
| stderr=subprocess.PIPE, |
| text=True, |
| ) |
| stdout, stderr = process.communicate() |
| if process.returncode != 0: |
| raise subprocess.CalledProcessError( |
| process.returncode, process.args, output=stdout, stderr=stderr |
| ) |
| print(stdout) |
For simple execution,
run() is usually easier. subprocess.call() also waits for the command and returns its exit code, but new code generally uses run().Legacy approaches
os.system()
python_snippet
Python · 4 lines|
| import os |
| status = os.system("ls -l") |
| print("Status:", status) |
os.system() runs a command through a shell and does not capture output as its return value. The returned status is platform-dependent; on Unix, it is an encoded wait status rather than a plain exit code. Use subprocess.run() when you need captured output or consistent status handling.os.popen()
python_snippet
Python · 6 lines|
| import os |
| with os.popen("ls -l") as stream: |
| output = stream.read() |
| print(output) |
os.popen() runs a shell command and provides a file object for reading standard output. Standard error is not captured by default. It is useful to recognize in older code, but subprocess is preferred for new code. Do not concatenate untrusted input into its command string.The Python 2 commands module
The Python 2
commands module was removed in Python 3. Python 3 offers subprocess.getstatusoutput() and subprocess.getoutput() as similar interfaces. They run command strings through a shell and combine standard output and standard error; prefer an argument list without a shell for untrusted input.Summary
- Use
subprocess.run()with an argument list for ordinary commands.
- Add
capture_output,check, andtimeoutwhen needed.
- Use
Popenfor more control over processes and pipes.
- Treat
os.system(),os.popen(), and Python 2'scommandsas legacy alternatives.
✦ 卷终 · 柯航存卷 ✦