subprocess module
The standard library module for running other programs from Python and collecting their output and exit code.
Building a shell command from user input with shell=True allows command injection.
In more detail
subprocess.run(["git", "status"], capture_output=True, text=True) runs a command and returns its result. Pass the command as a list rather than one string with shell=True, so user input can never be run as extra shell commands.
Example
import subprocess
subprocess.run(["python3", "--version"])Related terms
- os module — The standard library module for talking to the operating system: environment variables, the current directory, files and processes.
- exit code — A number a process returns when it finishes: 0 means success, anything else means something went wrong.
- process — A program that is currently running, with its own memory and a numeric identifier.
- child process — A process started by another process, its parent, from which it inherits a copy of the environment and current directory.
- argument vector — The list of separate strings a program is started with: its own name followed by each argument.
- command injection — An attack where input meant as data, such as a file name or form field, gets run as commands because a program built code from it.
Taught in
- What MCP Is — AI Engineering: LLM Apps, RAG & Agents
- Build An MCP Server — AI Engineering: LLM Apps, RAG & Agents
- A Standard Library Tour — Hands-on Python: Complete Video Course & Book
- The Environment Variable Trap — Application Security & Threat Modeling for Engineers
- Injection In All Its Forms — Application Security & Threat Modeling for Engineers
- Static Application Security Testing — Application Security & Threat Modeling for Engineers
- When awk Runs Out: Python Data Types, Modules And Virtual Environments For Admins — CompTIA Linux+ (XK0-006) Exam Prep