Skip to main content

isatty()

The isatty() method from File Methods in Python checks if the file is associated with a terminal device. It returns True if the file descriptor is open and connected to a tty (text terminal), otherwise it returns False.

Parameter Values

This function does not accept any parameters.

Return Values

The isatty() method returns a boolean value: True or False.

How to Use isatty() in Python

Example 1:

The isatty() method returns True if the file is connected to a terminal device, otherwise False.

file = open('test.txt', 'r')
print(file.isatty())
Example 2:

This method is commonly used to check if the input/output file is a terminal or a regular file.

file = open('test.txt', 'r')
if file.isatty():
    print('File is connected to a terminal')
else:
    print('File is not connected to a terminal')
Example 3:

It can be useful when writing Python scripts that need to determine the type of file being used for input or output.

import sys

if sys.stdin.isatty():
    print('Input is coming from a terminal')
else:
    print('Input is coming from a regular file')