Python subprocess Module
Example
Run a simple command and capture output:
import subprocess
result = subprocess.run(['echo', 'Hello from Emil'], capture_output=True, text=True)
print(result.stdout)
Try it Yourself »
Definition and Usage
The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain return codes.
Use it to execute external commands, run shell scripts, or interact with other programs from your Python code.
Members
Member | Description |
---|---|
CalledProcessError | Exception raised when a process returns a non-zero exit status. |
CompletedProcess | Object representing a finished process (returned by run()). |
DEVNULL | Special value for redirecting to /dev/null. |
PIPE | Special value for creating a new pipe to the child process. |
Popen | Class for more advanced process management. |
STDOUT | Special value for redirecting stderr to stdout. |
SubprocessError | Base exception for subprocess-related errors. |
TimeoutExpired | Exception raised when a timeout occurs. |
call() | Run command and wait for completion (legacy). |
check_call() | Run command and raise exception if it returns non-zero. |
check_output() | Run command and return its output. |
getoutput() | Run command in shell and return output (legacy). |
getstatusoutput() | Run command in shell and return (status, output) tuple. |
list2cmdline() | Convert argument list to command string (Windows). |
run() | Run command and return a CompletedProcess instance. |