Python os.isatty() 方法



Python 的 isatty() 方法如果指定的描述符是開啟的並且連線到類似“tty”的裝置,則返回 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 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!!")

當我們執行以上程式時,它會產生以下結果:

Returned value is:  False
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
python_files_io.htm
廣告