使用 Python 進行 POSIX 樣式 TTY 控制
termios 模組提供了一個與 POSIX 終端 I/O 控制的介面。它僅適用於 Unix 系統。
要使用 termios 模組,我們應該使用以下方法匯入它:
import termios
此模組中的所有方法都將檔案描述符作為引數。termios 模組有一些方法,它們是:
方法 termios.tcgetattr(fd)
此方法返回給定檔案描述符的 tty 屬性列表。屬性包括 iflag、oflag、cflag、lflag、ispeed、ospeed、cc。
方法 termios.tcsetattr(fd, when, attributes)
此方法用於從屬性列表中設定屬性。第二個引數確定何時更改屬性。when 部分有一些常量。它們是:
| 序號 | When 屬性 & 含義 |
|---|---|
| 1 | TCSANOW 立即更改屬性 |
| 2 | TCSADRAIN 傳輸所有排隊的輸出後更改屬性 |
| 3 | TCSAFLUSH 傳輸所有排隊的輸出後更改屬性,並丟棄所有排隊的輸入。 |
方法 termios.tcsendbreak(fd, duration)
它在檔案描述符上傳送中斷訊號。當持續時間為零時,它會發送 0.25-0.5 秒的中斷訊號。
方法 termios.tcdrain(fd)
此方法用於等待直到所有輸出寫入檔案描述符。
方法 termios.tcflush(fd, queue)
此方法用於丟棄 fd 上的佇列資料。佇列選擇器用於指定將在哪個佇列上執行此操作。TCIFLUSH 用於輸入佇列,TCOFLUSH 用於輸出佇列,TCIOFLUSH 用於兩者。
示例程式碼
import termios, sys
def get_password(prompt= "Enter Password: "):
file_desc = sys.stdin.fileno()
old_pass = termios.tcgetattr(file_desc)
new_pass = termios.tcgetattr(file_desc)
new_pass[3] & = ~termios.ECHO
try:
termios.tcsetattr(file_desc, termios.TCSADRAIN, new_pass)
password = input(prompt)
finally:
termios.tcsetattr(file_desc, termios.TCSADRAIN, old_pass)
return password
輸出
$ python3 example.py Enter Password: Entered Password: my_password
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP