如果指定的文件描述符已打开并连接到类似 “tty” 的设备,则 Python isatty() 方法返回 True,否则返回 False。该方法用于检查文件流的交互性。
“tty”之类的设备是指“电传打字机”终端。它是用于执行 I/O 操作的输入设备。文件描述符用于对文件进行数据读取或写入数据。
语法
isatty() 方法的语法如下所示 -
os.isatty( fd )
参数
Python os.isatty() 方法接受单个参数 -
- fd − 这是需要检查其关联的文件描述符。
返回值
Python os.isatty() 方法返回一个布尔值(True 或 False)。
例以下示例显示了 isatty() 方法的基本用法。在这里,我们打开一个文件并在其中写入二进制文本。然后,我们将验证文件是否连接到 tty 设备。
#!/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 qikepu")
# 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!!")
当我们运行上述程序时,它会产生以下结果——
Returned value is: False
File closed successfully!!
File closed successfully!!
例
要检查标准输出/输入是否连接到终端,我们可以将 1 和 0 分别作为参数传递给 isatty() 方法。下面的示例显示了相同的情况。
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")
在执行时,上述程序将显示以下输出 -
Standard output/input is connected to terminal

