Pseudo-terminal Utilities in Python

PythonProgrammingServer Side Programming

The Pseudo-terminal utility module pty is defined to handle pseudo-terminal concepts. Using this we can start another process, and also can read or write from controlling terminal using programs.

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

To use the pty module, we should import it using −

import pty

There are some modules of the pty module, these are −

Method pty.fork()

This method is used to connect the child controlling terminal to pseudo-terminal. This method returns the pid and the fd. The child process gets the pid 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 controlling terminal.

Method pty.openpty()

This method is used to open a new pseudo-terminal pair. It returns a file descriptor for the master and the slave.

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

The spawn process is used to connect its controlling terminal with current processes standard io. The master_read and stdin_read read from the file descriptor. The default size is 1024 bytes.

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

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
raja
Published on 31-Oct-2018 17:59:52
Advertisements