2 min read

Python Pty Module

The pty module defines operations for handling the pseudo-terminal concept: starting another process and being able to write to and read from its controlling terminal programmatically.

Note: The pty module is Linux/Unix specific and is not available on Windows.

Importing the Module

import pty

Spawning a Process

The pty.spawn() function spawns a process, and connects its controlling terminal with the current process's standard io. This is often used to wrap programs that insist on reading from a terminal.

import pty
import os

def read(fd):
    data = os.read(fd, 1024)
    return data

# Spawn 'ls'
pty.spawn(['ls', '-l'], read)

Opening a Pseudo-Terminal

pty.openpty() opens a new pseudo-terminal pair. It returns a pair of file descriptors (master, slave).

import pty
import os

master, slave = pty.openpty()

# Write to the slave
os.write(slave, b'Hello\n')

# Read from the master
print(os.read(master, 100))

Forking

pty.fork() connects a child process to a pseudo-terminal. It returns (pid, fd). pid is 0 in the child, and the child's PID in the parent. fd is the file descriptor of the master end of the pseudo-terminal.

import pty
import os

pid, fd = pty.fork()

if pid == 0:
    # Child process
    print("In child")
    # The child's stdout/stdin/stderr are connected to the slave pty
else:
    # Parent process
    print(f"In parent, child pid is {pid}")
    print(f"Output from child: {os.read(fd, 100)}")

programming/python/python