Python os.isatty() Method
os.isatty() Overview
The os.isatty() method is used to determine if the file descriptor fd is open and connected to a tty(-like) device, then it returns true, otherwise False.
os.isatty() Syntax
The isatty() method syntax format is as follows.
os.isatty()
os.isatty() Parameters
- None
os.isatty() Return Value
Returns true if the file descriptor fd is open and connected to a tty(-like) device, otherwise False.
os.isatty() Demo#1
The following example demonstrates the use of the isatty() method.
#!/usr/bin/python3
import os, sys
# Open file
fd = os.open( "apidemos.txt", os.O_RDWR|os.O_CREAT )
# Write strings
str = "This is apidemos.com website"
os.write(fd,bytes(str, 'UTF-8'))
# Use isatty() to view the file
ret = os.isatty(fd)
print ("os.isatty return value: ", ret)
# close file
os.close( fd )
Output:
os.isatty() Demo#2
Use of os.isatty() method to check if the given file descriptor is open and connected to tty(-like) device or not
# Python program to explain os.isatty() method in apidemos.com
# importing os module
import os
# Create a pipe using os.pipe() method
# It will return a pair of
# file descriptors (r, w) usable for
# reading and writing, respectively.
r, w = os.pipe()
# Check if file descriptor r
# is open and connected
# to a tty(-like) device
# using os.isatty() method
print("Connected to a terminal:", os.isatty(r))
# 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
master, slave = os.openpty()
# Check if file descriptor master
# is open and connected
# to a tty(-like) device
# using os.isatty() method
print("Connected to a terminal:", os.isatty(master))
Output: