
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Open New Pseudo Terminal Pair Using Python
Pseudo-terminals (pty) are an advanced and powerful technique in Python when we are dealing with terminal-based processes or simulating interactive sessions programmatically.
A pseudo-terminal allows a process to connect to a real terminal. Python provides a built-in pty module that helps in creating and managing these terminal pairs. In this article, we will learn how to open a new pseudo-terminal pair using Python.
Using pty.openpty()
The pty module in Python provides the openpty() function that returns a tuple containing file descriptors for the master and slave ends of a new pseudo-terminal pair.
Example
Following is an example, which shows how to create a new pty pair using pty.openpty() -
import os import pty # Open a new pseudo-terminal pair master_fd, slave_fd = pty.openpty() # Get the name of the slave device slave_name = os.ttyname(slave_fd) print("Master FD:", master_fd) print("Slave FD:", slave_fd) print("Slave device path:", slave_name)
Following is the output of the above program -
Master FD: 3 Slave FD: 4 Slave device path: /dev/pts/3
Using pty to Spawn a Shell
The other method available in Python is Spawn a shell that is connected to the slave end of the pseudo-terminal. This is useful for terminal emulation or sandboxing shell processes.
Example
Following is an example that shows how to spawn a shell and interact with it through the master end of the pty -
import os import pty import subprocess master_fd, slave_fd = pty.openpty() # Start a shell connected to the slave proc = subprocess.Popen( ['/bin/bash'], stdin=slave_fd, stdout=slave_fd, stderr=slave_fd, close_fds=True ) # Interact with the shell through the master os.write(master_fd, b'echo Hello from pty\n') output = os.read(master_fd, 1024) print("Shell Output:", output.decode())
When we run the above program, a new bash shell is started, and it prints the message from our Python script -
Shell Output: Hello from pty
Finally, we can conclude, opening a pty pair in Python is straightforward and useful for many advanced usecases -
- We can use pty.openpty() to create a low-level terminal emulation channel.
- We can use os.ttyname() to identify the slave terminal path.
- We can connect subprocesses, such as shells, to the slave end to simulate terminal sessions.
Note: The pty module is available only on Unix-like systems and is not supported on Windows. When we want to use the pseudo-terminal pair in Windows, we can use the pywinpty on Windows 10+.