Running Commands with subprocess
Execute external programs.
Running Commands with subprocess is a free Python Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is subprocess?
The subprocess module lets your Python program run external commands and other programs, just like typing them in a terminal.
import subprocess
result = subprocess.run(['echo', 'hello'])
print('return code:', result.returncode)subprocess.run Basics
subprocess.run() is the recommended entry point. You pass the command as a list of arguments: the program name first, then each argument separately.
import subprocess
result = subprocess.run(['echo', 'one', 'two'])
print('done with code', result.returncode)Why a List, Not a String?
Passing a list avoids the shell parsing your command, which prevents quoting bugs and shell-injection risks. Each element is one argument.
import subprocess
# Safe: each piece is its own argument
subprocess.run(['echo', 'a file with spaces.txt'])The CompletedProcess Object
run() returns a CompletedProcess holding the args, returncode, and (if captured) output. Code 0 means success.
import subprocess
cp = subprocess.run(['true'])
print('args:', cp.args)
print('returncode:', cp.returncode)Checking Return Codes
A non-zero return code usually means the command failed. You can inspect it manually after the call.
import subprocess
cp = subprocess.run(['ls', '/no/such/path'])
if cp.returncode != 0:
print('command failed with', cp.returncode)Raising on Failure with check=True
Pass check=True to make run() raise CalledProcessError automatically when the command exits non-zero.
import subprocess
try:
subprocess.run(['false'], check=True)
except subprocess.CalledProcessError as e:
print('failed with code', e.returncode)Passing Arguments
Extra command arguments are just more list items. Here we list a directory in long format.
import subprocess
subprocess.run(['echo', '-n', 'no newline'])
print()
print('above echo had -n flag')Setting a Timeout
Use timeout to abort a command that runs too long. It raises TimeoutExpired.
import subprocess
try:
subprocess.run(['sleep', '5'], timeout=0.1)
except subprocess.TimeoutExpired:
print('command took too long, aborted')Working Directory
The cwd argument runs the command in a specific directory without changing your program's own working directory.
import subprocess
subprocess.run(['pwd'], cwd='/tmp')The shell=True Option
With shell=True you pass a single command string the shell interprets. It enables pipes and globs but is risky with untrusted input. Prefer the list form.
import subprocess
subprocess.run('echo hello && echo world', shell=True)Avoiding os.system
The old os.system only returns an exit code and offers no safe argument passing or output capture. subprocess.run replaces it for all new code.
import subprocess
# Modern, safe approach
cp = subprocess.run(['echo', 'modern way'])
print('exit code:', cp.returncode)Quick Check
Test your understanding of running commands.
Recap
You learned to run commands with subprocess:
subprocess.run([...])runs an external program safely.- It returns a
CompletedProcesswithreturncode. check=Trueraises on failure;timeoutaborts slow commands.- Prefer the list form over
shell=True.
Next: capturing the command's output.
Frequently asked questions
Is the “Running Commands with subprocess” lesson free?
Yes — the full text of “Running Commands with subprocess” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.
What will I learn in “Running Commands with subprocess”?
Execute external programs. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Python Academy?
No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Running Commands with subprocess” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Python Academy lesson?
Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Running Commands with subprocess
- Capturing Output
- Environment and os Module
- shutil for File Operations