English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Pseudo Terminal Utility in Python

The pseudo terminal utility module pty is defined to handle the pseudo terminal concept. Using this feature, we can start another process, or use programs to read or write from the control terminal.

This module is highly platform-oriented. We should use UNIX systems to perform these operations.

To use the pty module, we should use-Import it

import pty

There are some modules in the pty module, which are-

Method pty.fork()

This method is used to connect the child control terminal to the pseudo terminal. This method returns pid and fd. The pid of the child process is 0, but the fd is invalid. The return value of the parent is the pid of the child process, and the fd holds the child control terminal.

Method pty.openpty()

This method is used to open a new pseudo terminal pair. It returns the file descriptors for the host and the slave.

Method pty.spawn(argv [,master_read [,stdin_read]])

The generation process is used to connect the control terminal of the current process with the standard io of the current process. Reads master_read and stdin_read from the file descriptor. The default size is1024Bytes.

Example Code

import pty, os
def process_parent_child():
   (process_id, fd) = pty.fork()
   print("The Process ID for the Current process is: " + str(os.getpid())
   print("The Process ID for the Child process is: " + str(process_id)
process_parent_child()
master, slave = pty.openpty()
print('Name of the Master: ' + str(os.ttyname(master))
print('Name of the Slave: ' + str(os.ttyname(slave))

Output Result

The Process ID for the Current process is: 12508
The Process ID for the Child process is: 12509
Name of the Master: /dev/ptmx
Name of the Slave: /dev/pts/2