Python 3.0+subprocessfunction
subprocess.getoutput()
shell invocation
Runs a command string through the system shell and returns its output (stdout merged with stderr) as one string.
Syntax
subprocess.getoutput(cmd, *, encoding=None, errors=None)
The exit status is thrown away: a failing command returns its error text as an ordinary result with no way to tell — use getstatusoutput() for that. The command goes through the shell (sh on Unix, cmd.exe on Windows), so the syntax differs, and user input pasted into it is an injection hole. One trailing newline is stripped, and the output is decoded with the locale encoding (UTF-8 since 3.15) unless encoding is passed.
Examples
import subprocess, sys
# двойные кавычки понимают и sh, и cmd.exe
cmd = f'"{sys.executable}" -c "print(42)"'
print(repr(subprocess.getoutput(cmd))) # → '42' — без перевода строки
import subprocess, sys
cmd = f'"{sys.executable}" -c "import sys; sys.exit(1)"'
print(repr(subprocess.getoutput(cmd))) # → '' — о сбое ни слова
See also
Open in the full glossarydocs.python.orgReport an inaccuracy