Python Glossary Русский

all Python 3osfunction

os.popen

os — processes

Opens a pipe to a shell command and returns a file object to read its output or write its input.

Syntax

os.popen(...)

It wraps subprocess.Popen with shell=True: the command string goes to a shell, and user data in it invites command injection. close() returns None on success, otherwise an encoded status — on Unix convert it with waitstatus_to_exitcode. A failing command raises no exception; for checks subprocess.run(..., check=True) is handier.

Examples

import os
print(os.popen('echo hello').read().strip())   # → hello
stream = os.popen('echo hello')   # канал открыт на чтение вывода команды
print(stream.read() == 'hello\n')   # → True — в конце вывода остаётся перевод строки
print(stream.close())   # → None — команда завершилась с кодом 0
print(os.popen('exit 3').close())   # → ненулевой статус: на Unix 768 (3 << 8), на Windows 3

See also

Open in the full glossarydocs.python.orgReport an inaccuracy