Python os.ttyname() Method
os.ttyname() Overview
The os.ttyname() method is used to return a string that represents the end device associated with the file descriptor fd. If fd is not associated with a terminal device, an exception is raised.
os.ttyname() Syntax
The ttyname() method syntax format is as follows:
os.ttyname(fd)
os.ttyname() Parameters
- fd – file descriptor
os.ttyname() Return Value
Returns a string that represents the terminal device associated with the file descriptor fd.
os.ttyname() Example#1
The following example demonstrates the use of the ttyname() method.
- Standard file descriptors
- i.e 0 (stdin), 1 (stdout), and 2 (stderr) are used by our program. Get the terminal device associated with these file descriptor.
- Open a new pseudo-terminal pair using os.openpty() method
- It will return master and slave file descriptor for pty ( pseudo terminal device) and tty ( native terminal device) respectively
import os
print("Standard input os.ttyname(0):", os.ttyname(0))
print("Standard output os.ttyname(1):", os.ttyname(1))
print("standard error os.ttyname(2)", os.ttyname(2))
master, slave = os.openpty()
print("Master os.ttyname(master):", os.ttyname(master))
print("Slave os.ttyname(slave):", os.ttyname(slave))
Output:
os.ttyname() Example#2
If the specified file descriptor is not associated with any terminal device, then an exception will be raised.
For example:
- Create a pipe using os.pipe() method It will return a pair of file descriptors (r, w) usable for reading and writing, respectively. Get the terminal device associated with the file descriptor r or w
import os
r, w = os.pipe()
print(os.ttyname(r))
Output:
os.ttyname() Example#3
Create a pipe using os.pipe() method It will return a pair of file descriptors (r, w) usable for reading and writing, respectively.
- Method 1 (using exception handling technique)
- Try to get the terminal device associated with the file descriptor r or w
- Method 2 (using os.isatty() method)
- check first if the file descriptor w is associated with a tty(-like) device or not, if it is then only get the terminal device associated with it
import os
r, w = os.pipe()
# Method 1
try :
print(os.ttyname(r))
except OSError as error :
print(error)
print("File descriptor is not associated with any terminal device by os.ttyname(r)")
# Method 2
if os.isatty(w) :
print(os.ttyname(w))
else :
print("File descriptor is not associated with any terminal device by os.ttyname(w)")
Output: