Python Glossary Русский

all Python 3subprocessfunction

subprocess.check_output()

running processes

Runs a command and returns its stdout as bytes (or as a str with text=True). A non-zero exit code raises CalledProcessError.

Syntax

subprocess.check_output(args, *, text=False, stderr=None, timeout=None, ...)

Only stdout is captured — stderr goes straight to the parent's console by default, so the actual error message is easy to lose; catch CalledProcessError and inspect e.returncode and e.output, or pass stderr=subprocess.STDOUT. It is a thin wrapper over subprocess.run(..., check=True, stdout=PIPE) left over from pre-3.5 days, and the docs point new code at run(). Without text=True you get bytes back, and comparing that to a normal string silently yields False.

Examples

import subprocess
out = subprocess.check_output(['python3', '--version'], text=True)
print(out)  # Python 3.x.y
try:
    subprocess.check_output(['false'])  # команда, возвращающая 1
except subprocess.CalledProcessError as e:
    print('код возврата:', e.returncode)

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy