How to Use subprocess Module in Python: Syntax and Examples
Use the
subprocess module in Python to run system commands by calling functions like subprocess.run(). This lets you execute commands, capture their output, and check for errors easily within your Python code.Syntax
The main function to run commands is subprocess.run(). It takes a list of command arguments and optional parameters to control input, output, and error handling.
args: List of command and arguments, e.g.,["ls", "-l"].capture_output=True: Captures standard output and error.text=True: Returns output as string instead of bytes.check=True: Raises an error if the command fails.
python
import subprocess result = subprocess.run(["echo", "Hello, world!"], capture_output=True, text=True) print(result.stdout)
Output
Hello, world!
Example
This example runs the ls -l command to list files in the current directory with details. It captures and prints the output.
python
import subprocess try: result = subprocess.run(["ls", "-l"], capture_output=True, text=True, check=True) print("Command output:\n" + result.stdout) except subprocess.CalledProcessError as e: print(f"Command failed with exit code {e.returncode}")
Output
Command output:
(total output of ls -l command showing files and details)
Common Pitfalls
Common mistakes include:
- Passing the command as a single string without
shell=True, which causes errors. - Not using
capture_output=Truewhen you want to get the command output. - Ignoring errors by not using
check=True, which can hide failures.
Always prefer passing commands as a list to avoid shell injection risks.
python
import subprocess # Wrong way: passing command as string without shell=True # subprocess.run("ls -l") # This will raise an error # Right way: subprocess.run(["ls", "-l"]) # Or if you want to use shell features (less safe): subprocess.run("ls -l", shell=True)
Quick Reference
| Parameter | Description |
|---|---|
| args | List of command and arguments to run |
| capture_output | Set to True to capture stdout and stderr |
| text | Set to True to get output as string instead of bytes |
| check | Set to True to raise error if command fails |
| shell | Set to True to run command through the shell (use carefully) |
Key Takeaways
Use subprocess.run() with a list of arguments to run system commands safely.
Set capture_output=True and text=True to get command output as a string.
Use check=True to catch errors when commands fail.
Avoid shell=True unless necessary to reduce security risks.
Always handle exceptions to manage command failures gracefully.