Python Glossary Русский

Python 3.5+subprocessterm

subprocess.CompletedProcess

running processes

The result of subprocess.run(): the launch arguments, the exit status and the captured stdout and stderr of a finished process.

Syntax

result = subprocess.run(args, ...)  # result.args, .returncode, .stdout, .stderr

A non-zero returncode raises nothing on its own — test it or call check_returncode(), which raises CalledProcessError. stdout and stderr are None when output was not captured and hold bytes unless text=True or an encoding was passed. Output almost always ends with a newline, so compare it after .strip().

Examples

import subprocess, sys
r = subprocess.run([sys.executable, '-c', 'print(42)'],
                   capture_output=True, text=True)
print(r.returncode)  # → 0
print(repr(r.stdout))  # → '42\n'
print(r.stderr == '')  # → True
import subprocess, sys
r = subprocess.run([sys.executable, '-c', 'import sys; sys.exit(1)'])
print(r.stdout)  # → None — вывод не перехватывали
try:
    r.check_returncode()
except subprocess.CalledProcessError as e:
    print(e.returncode)  # → 1

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy