Python | os.ttyname() method
Last Updated :
25 Jun, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.ttyname()
method in Python is used to get the terminal device associated with the specified file descriptor.
A file descriptor is small integer value that corresponds to a file or other input/output resource, such as a pipe or network socket. It is an abstract indicator of a resource and act as handle to perform various lower level I/O operations like read, write, send etc.
For Example: Standard input is usually file descriptor with value 0, standard output is usually file descriptor with value 1 and standard error is usually file descriptor with value 2. These file descriptors i.e 0 (stdin), 1 (stdout), and 2 (stderr) are standard file descriptors used by our programs. Further files opened by the current process will get the value 3, 4, 5 an so on.
Note: This method is only available on UNIX platforms and an exception is raised if the specified file descriptor is not associated with any terminal device.
Syntax: os.ttyname(fd)
Parameter:
fd: A file descriptor
Return Type: This method returns a string value which represents the terminal device associated with the specified file descriptor fd.
Code #1: Use of os.ttyname() method to get the terminal device associated with a file descriptor.
import os
print ( "Terminal device associated with:" )
print ( "Standard input:" , os.ttyname( 0 ))
print ( "Standard output:" , os.ttyname( 1 ))
print ( "standard error" , os.ttyname( 2 ))
master, slave = os.openpty()
print ( "Master:" , os.ttyname(master))
print ( "Slave:" , os.ttyname(slave))
|
Output:
Terminal device associated with:
Standard input: /dev/pts/0
Standard output: /dev/pts/0
standard error /dev/pts/0
Master: /dev/ptmx
Slave: /dev/pts/1
Code #2: If the specified file descriptor is not associated with any terminal device
import os
r, w = os.pipe()
print (os.ttyname(r))
|
Output:
Traceback (most recent call last):
File "getTerminalDevice.py", line 20, in
print(os.ttyname(r))
OSError: [Errno 25] Inappropriate ioctl for device
Code #3: Way to handle the above raised exception
import os
r, w = os.pipe()
try :
print (os.ttyname(r))
except OSError as error :
print (error)
print ( "File descriptor is not associated with any terminal device" )
if os.isatty(w) :
print (os.ttyname(w))
else :
print ( "File descriptor is not associated with any terminal device" )
|
Output:
[Errno 25] Inappropriate ioctl for device
File descriptor is not associated with any terminal device
File descriptor is not associated with any terminal device
Share your thoughts in the comments
Please Login to comment...