subprocess.run
- Version
- 3.14
- Since
- 3.5
- Review
- Draft
Summary#
subprocess.run starts a program, waits for it and returns a CompletedProcess. With the default shell=False, pass arguments as a list to supply each one separately to the program.
Syntax#
result = subprocess.run(
[program, argument],
capture_output=True,
text=True,
check=True,
timeout=30,
)
Example#
import subprocess
import sys
echo = "import sys; print(sys.argv[1])"
result = subprocess.run(
[sys.executable, "-I", "-c", echo, "two words; echo injected"],
capture_output=True,
text=True,
check=True,
timeout=30,
)
print(result.returncode, result.stdout.strip())
try:
subprocess.run([sys.executable, "-I", "-c", "raise SystemExit(3)"], check=True)
except subprocess.CalledProcessError as error:
print("failed with", error.returncode)
Expected output#
0 two words; echo injected
failed with 3
Common mistakes#
A nonzero exit status does not raise unless you pass check=True. Keep the default shell=False and pass a list when starting an executable with untrusted arguments. Windows may start .bat and .cmd files through a shell even with shell=False, so use an executable directly when you need to pass arbitrary text.
Version applicability#
subprocess.run was added in Python 3.5. The child interpreter's -I option is available from 3.4. The capture_output and text parameters set the minimum for both snippets at Python 3.7.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0