The Python subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. Use it to run a shell command or an executable in Python.
The Python subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.
If you want to run Python code in a separate process consider multiprocessing instead.
pexpect is preferable to subprocess
in some cases.
Waiting for a command to finish and getting the result
- How to execute a program or call a system command? (
check_call()
) - Running shell command and capturing the output (
check_output()
) - How do I pass a string into subprocess.Popen (using the stdin argument)? (
run()
,.communicate()
) - How do I use subprocess.Popen to connect multiple processes by pipes? (
a | b | c
shell pipeline) - [advanced] Multiple pipes in subprocess (bash process substitution:
a <(b) <(c)
)
Interacting with a subprocess while it is still running
- Read streaming input from subprocess.communicate() (
for line in process.stdout
) - Displaying subprocess output to stdout and redirecting it
- A non-blocking read on a subprocess.PIPE in Python
- Run command and get its stdout, stderr separately in near real time like in a terminal (buffering/concurrency:
threading
,asyncio
,pty
,select
) - Dialog-based interaction (multiple dynamic requests/responses) (
pexpect
) - How to properly interact with a process using subprocess module (explanation for a block-buffering issue)
Windows
Misc
- Python subprocess arguments (use
shlex.split()
to convert a string to a list of arguments) - Using module 'subprocess' with timeout (
timeout=seconds
) - How to get exit code when using Python subprocess communicate method? (
.returncode
) - How to hide output of subprocess (
stdout=DEVNULL
) - How to terminate a python subprocess launched with shell=True (
start_new_session=True
+os.killpg
) - Python threading multiple bash subprocesses?
- Python: execute cat subprocess in parallel (
ThreadPool
orasyncio
)