方法簽名
file.isatty() -> bool
回傳值
True:檔案連接至終端機裝置(TTY),如互動式終端機、虛擬終端、SSH session。
False:一般檔案、管道、重導向、Socket 等。
範例
with open("foo.txt", "w") as f:
print(f.isatty()) # False
import sys
print(sys.stdin.isatty()) # True (互動式終端機)
print(sys.stdout.isatty()) # True
print(sys.stderr.isatty()) # True
# 管道/重導向時
# $ python script.py < input.txt
# sys.stdin.isatty() → False
# $ python script.py | grep foo
# sys.stdout.isatty() → False
實際應用場景
- 彩色輸出控制:僅在 TTY 輸出 ANSI 色碼,避免導向檔案/管道時產生亂碼。
- 進度條/互動提示:
tqdm、click、prompt_toolkit 內部皆用 isatty() 判斷是否啟用豐富介面。
- 行緩衝 vs 區塊緩衝:TTY 通常預設行緩衝,非 TTY 為區塊緩衝,影響
print(flush=True) 必要性。
程式碼範例:智慧型彩色輸出
import sys
def colorize(text, color_code):
if sys.stdout.isatty():
return f"\033[{color_code}m{text}\033[0m"
return text
print(colorize("錯誤訊息", "31")) # 紅色 (僅終端機顯色)
print(colorize("成功訊息", "32")) # 綠色
常見誤區
- 以為
isatty() 能偵測「是否為檔案」→ 錯誤,它偵測的是「是否為終端機」。
/dev/null、/dev/zero 等特殊裝置檔案也會回傳 False。
- Windows
NUL 裝置同樣為 False。