subprocess
Popen
run
Python
programming

subprocess.Popen vs subprocess.run in Python

Codemia Knowledge Hub ·

subprocess.run() is the high-level API: it starts a command, waits for it to finish and returns the result. subprocess.Popen() is the lower-level API that run() is built on: it starts the process and returns immediately, leaving you to decide when to wait and how to handle its pipes. Use run() for one-shot commands and Popen() for streaming I/O, background execution, pipelines or manual lifecycle control.

subprocess.run() blocks and returns a CompletedProcess

python
1import subprocess
2
3result = subprocess.run(
4    ["python", "--version"],
5    capture_output=True,
6    text=True,
7    check=False,
8)
9
10print(result.returncode)
11print(result.stdout)
12print(result.stderr)

This is the modern default for straightforward command execution. It is readable, and safe when you pass an argument list.

To raise an exception automatically when the command fails:

python
subprocess.run(["false"], check=True)

That raises CalledProcessError if the exit code is non-zero.

subprocess.Popen() returns a process object immediately

python
1import subprocess
2
3proc = subprocess.Popen(
4    ["python", "-c", "import time; time.sleep(2); print('done')"],
5    stdout=subprocess.PIPE,
6    stderr=subprocess.PIPE,
7    text=True,
8)
9
10stdout, stderr = proc.communicate()
11print(proc.returncode)
12print(stdout)

It is more verbose, but you decide when to wait, how to read output, whether to poll, and how to combine several child processes. Using it where run() would do just adds complexity.

Choosing between them

Use run() when all of these are true:

  • you want to wait for completion immediately
  • you do not need interactive communication while the process runs
  • you want the simplest API

Use Popen() when you need at least one of these:

  • process starts in the background
  • stdout or stderr must be handled incrementally
  • the child process needs interactive input
  • you are building a pipeline or supervising several processes

run() wraps the common "start, wait, capture, return" workflow around the same machinery, which is why many older Popen() examples read more clearly when rewritten with run().

Streaming output line by line with Popen()

run() cannot show output while the process is still running. Popen() can:

python
1import subprocess
2
3proc = subprocess.Popen(
4    ["python", "-u", "-c", "for i in range(3): print(i)"],
5    stdout=subprocess.PIPE,
6    text=True,
7)
8
9for line in proc.stdout:
10    print(f"child said: {line.strip()}")
11
12proc.wait()

This is useful for long-running jobs, build tools and anything where you want live progress instead of the final output buffer.

Polling a background process

Popen() also fits when the parent has other work to do while the child runs:

python
1import subprocess
2import time
3
4proc = subprocess.Popen(["python", "-c", "import time; time.sleep(5)"])
5
6while proc.poll() is None:
7    print("still running")
8    time.sleep(1)
9
10print("finished with", proc.returncode)

That would be awkward with run(), because run() blocks until completion.

Pipe deadlocks and shell=True

With Popen(), always consume or redirect the pipes you open. If the child writes enough data to a pipe that nobody reads, it blocks.

Be careful with shell=True in either API. If parts of the command come from user input, passing an argument list is safer than a single shell string.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms