Standard Library
Python subprocess Module
Python External Commands
Python subprocess module runs commands, avoiding shell=True.
What is the subprocess Module?
The subprocess module in Python is a powerful tool that allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module is a more secure and flexible alternative to older functions like os.system()
or os.spawn*()
. It helps you run shell commands directly from your Python scripts without setting shell=True
, which can pose security risks.
Basic Usage of subprocess.run()
The subprocess.run()
function is the recommended method for running commands in a subprocess. It returns a CompletedProcess
instance, which includes information about the executed command, such as its exit code and output. Here is a basic example:
Handling Errors with subprocess
When a command fails, you might want to handle the error gracefully. By setting the check
parameter to True
, a CalledProcessError
exception is raised if the command exits with a non-zero status:
Capturing Output
To capture the output of a command, use the capture_output=True
parameter. This captures standard output and standard error, which you can access via the stdout
and stderr
attributes of the result:
Passing Input to a Command
If a command requires input, you can pass it using the input
parameter. Here is an example that uses the echo
command:
Best Practices
- Avoid using
shell=True
, as it can introduce security vulnerabilities, especially if you're passing user input. - Use
subprocess.run()
for most use cases. It is simple and returns aCompletedProcess
object. - Always handle exceptions such as
subprocess.CalledProcessError
to account for command failures.
Standard Library
- datetime Module
- math Module
- random Module
- os Module
- sys Module
- json Module
- re Module
- time Module
- collections Module
- itertools Module
- argparse Module
- logging Module
- urllib Module
- shutil Module
- glob Module
- statistics Module
- calendar Module
- zipfile Module
- pickle Module
- threading Module
- subprocess Module
- Requests Module
- cMath Module
- Previous
- threading Module
- Next
- Requests Module