subprocess | Python Standard Library – Real Python
The Python subprocess module allows you to spawn new processes, connect to their input, output, and error pipes, and obtain their return codes. It’s a powerful tool for running and controlling external programs within a Python script.
Here’s a quick example:
Key Features
- Runs and controls external processes
- Captures standard output and error streams
- Supports for piping data to and from processes
- Checks process return codes
Frequently Used Classes and Functions
Examples
Running a simple command and capturing its output:
Executing a command and checking its return code:
Capturing the output:
Using a Popen object for fine-grained control over input/output (I/O) streams:
Common Use Cases
- Automating shell command execution from Python
- Capturing and processing the output of shell commands
- Handling error codes returned by processes
- Piping data between Python and external commands
Real-World Example
Suppose you need to automate the process of converting Markdown files to HTML using the pandoc command. You can use the subprocess module to run pandoc from your Python script:
In this example, you use the subprocess module to automate the Markdown-to-HTML conversion process and handle any errors that might occur. Note that if you don’t have pandoc installed, then you’ll get a FileNotFoundError exception.
For additional information on related topics, take a look at the following resources:
- Using the Python subprocess Module (Course)