← Back to Python, page 5

python-0087 · Medium mid

How do you use subprocess safely to run an external command and capture its output?

Use subprocess.run with a list of arguments, capture_output=True, text=True, a timeout and check=True. Passing a list avoids the shell, so arguments containing spaces or characters such as ; are not interpreted. Avoid shell=True with any user input, and handle CalledProcessError and TimeoutExpired.

Full answer
python
import subprocess, sys

r = subprocess.run([sys.executable, "-c", "import sys; print(sys.argv[1])", "report; rm -rf /"],
                   capture_output=True, text=True, timeout=10, check=True)
print(repr(r.stdout), r.returncode)

try:
    subprocess.run([sys.executable, "-c", "raise SystemExit(3)"], capture_output=True, text=True, check=True, timeout=10)
except subprocess.CalledProcessError as e:
    print("CalledProcessError, exit code", e.returncode)

try:
    subprocess.run([sys.executable, "-c", "import time; time.sleep(5)"], timeout=0.2)
except subprocess.TimeoutExpired:
    print("TimeoutExpired")

Output:

text
'report; rm -rf /\n' 0
CalledProcessError, exit code 3
TimeoutExpired

The argument report; rm -rf / reaches the child as one harmless string because no shell parses it; with shell=True and string formatting, the shell would treat ; as a command separator. check=True turns a non-zero exit into CalledProcessError, and timeout kills a hung child and raises TimeoutExpired. text=True decodes output as text. Using sys.executable keeps the example portable.

python
import subprocess, sys

r = subprocess.run([sys.executable, "-c", "import sys; print(sys.argv[1])", "report; rm -rf /"],
                   capture_output=True, text=True, timeout=10, check=True)
print(repr(r.stdout), r.returncode)

try:
    subprocess.run([sys.executable, "-c", "raise SystemExit(3)"], capture_output=True, text=True, check=True, timeout=10)
except subprocess.CalledProcessError as e:
    print("CalledProcessError, exit code", e.returncode)

try:
    subprocess.run([sys.executable, "-c", "import time; time.sleep(5)"], timeout=0.2)
except subprocess.TimeoutExpired:
    print("TimeoutExpired")

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Pass arguments as a list
  • Avoid shell=True with input
  • check=True raises on failure
  • Always set a timeout
  • capture_output with text=True

Common mistakes

  • Formatting user input into shell strings
  • No timeout on external commands

Follow-ups

  • How do you stream output from a long-running process?
  • When is shell=True acceptable?

Tips

  • Show the injection attempt