Python os.isatty() Method



The Python isatty() method returns True if the specified file descriptor is open and connected to a "tty" like device, else False. This method is used for checking interactivity of a file stream.

The "tty" like device refers to "teletypewriter" terminals. It is an input device that is used to perform I/O operations. The file descriptor is used to read or write data to the file.

Syntax

The syntax for isatty() method is shown below −

os.isatty( fd )

Parameters

The Python os.isatty() method accepts a single parameter −

  • fd − This is the file descriptor for which association needs to be checked.

Return Value

The Python os.isatty() method returns a Boolean value (either True or False).

Example

The following example shows the basic use of isatty() method. Here, we are opening a file and writing binary text in it. Then, we are verifying if the file is connected to a tty device or not.

#!/usr/bin/python
import os, sys

# Open a file
fd = os.open("foo.txt", os.O_RDWR|os.O_CREAT )

# Write one string
os.write(fd, b"Python with Tutorialspoint")

# Now use isatty() to check the file.
ret = os.isatty(fd)

print ("Returned value is: ", ret)

# Close opened file
os.close( fd )
print("File closed successfully!!")

When we run above program, it produces the following result −

Returned value is:  False
File closed successfully!!

Example

To check whether standard output/input is connected to a terminal, we can pass 1 and 0 respectively as arguments to isatty() method. The following example shows the same.

import os

# Checking if standard output/input is connected to terminal
if os.isatty(1 and 0):
   print("Standard output/input is connected to terminal")
else:
   print("Standard output/input is not connected to a terminal")    

On executing, the above program will display the following output −

Standard output/input is connected to terminal
python_files_io.htm
Advertisements