all Python 3Linux · macOSosfunction
os.forkpty
os — process creation
Like fork, but the child gets a new pseudo-terminal; returns (pid, fd). Availability: Unix.
Syntax
os.forkpty(...)
The child gets a new pseudo-terminal, so programs inside behave as in a real terminal: they enable colour, line buffering and prompt for input. The parent reads and writes through the returned descriptor. The pty module is handier for this, and the third-party pexpect for automating program dialogues.
Examples
import os
pid, fd = os.forkpty() # → ? только Unix: в родителе (PID потомка, дескриптор мастер-конца pty), в потомке (0, -1)
if pid == 0: os.execvp('ls', ['ls', '-1']) # → ? потомок подменяется командой; в отличие от os.fork() её stdin/stdout — настоящий терминал, поэтому работают программы, требующие tty
print(os.read(fd, 1024)) # → ? только в родителе: вывод потомка, например b'file1\r\nfile2\r\n' — в pty перевод строки приходит как \r\n
print(os.waitpid(pid, 0)) # → ? (PID потомка, 0) — команда отработала и завершилась с кодом 0
os.read(fd, 1024) # → ? после завершения потомка на Linux: OSError [Errno 5] Input/output error, а не пустые байты
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy