Standard Library
Subprocesses
subprocess.run spawns a child Python interpreter, captures its stdout and stderr (capture_output=True), decodes them as text (text=True), and raises CalledProcessError if the child exits non-zero (check=True). The returned result holds the captured streams and exit code as portable evidence the child ran. (This fragment runs in standard Python only — the Python By Example runner does not provide child processes.)
Standard Python
result = subprocess.run(
[sys.executable, "-c", "print('child process')"],
text=True,
capture_output=True,
check=True,
)subprocess.run() starts a child process and waits for it. capture_output=True stores the child's standard output and error streams on the result object.
Source
import subprocess
import sys
result = subprocess.run(
[sys.executable, "-c", "print('child process')"],
text=True,
capture_output=True,
check=True,
)
print(result.stdout.strip())
print(result.returncode)Output
child process
0Notes
- Use a list of arguments instead of shell strings when possible.
- Capture output when the parent program needs to inspect it.
check=Trueturns non-zero exits into exceptions.- If you run this in local/server Python, the child process is real; on this site, the runnable evidence preserves the API shape without spawning a process.
See also
- prerequisite: Virtual Environments
- related: Networking
- related: Threads and Processes
Run the complete example
Expected output
child process
0
Execution time appears here after you run the example.