Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

POSIX TTY Control ใน Python (โมดูล termios)

โมดูล termios ให้ Interface ไปยัง POSIX TTY I/O Control ระดับต่ำ ควบคุม Terminal Attribute ทุกอย่างได้เฉพาะ UNIX

import termios


เมธอดหลัก

termios.tcgetattr(fd)

คืน List ของ Terminal Attributes: [iflag, oflag, cflag, lflag, ispeed, ospeed, cc]

termios.tcsetattr(fd, when, attributes)

ตั้งค่า Attributes

  • when: TCSANOW (ทันที), TCSADRAIN (รอ Output), TCSAFLUSH (รอ Output + Flush Input)

termios.tcsendbreak(fd, duration)

ส่ง Break Signal (duration=0 -> 0.25-0.5 วินาที)

termios.tcdrain(fd)

รอจน Output ทั้งหมดถูกส่งออก

termios.tcflush(fd, queue)

Flush Queue: TCIFLUSH (Input), TCOFLUSH (Output), TCIOFLUSH (ทั้งคู่)


Attribute Flags (บางส่วนสำคัญ)

Local Mode Flags (lflag)

Flagความหมาย
ECHOEcho Input Characters
ICANONCanonical Mode (Line Buffering)
ISIGEnable Signals (Ctrl+C, Ctrl+Z)
IEXTENExtended Functions

ตัวอย่าง: Password Input แบบไม่แสดงตัวอักษร

import termios, sys

def get_password(prompt="Enter Password: "):
    fd = sys.stdin.fileno()
    old_attrs = termios.tcgetattr(fd)
    new_attrs = termios.tcgetattr(fd)
    
    # ปิด ECHO
    new_attrs[3] &= ~termios.ECHO  # lflag index = 3
    
    try:
        termios.tcsetattr(fd, termios.TCSADRAIN, new_attrs)
        password = input(prompt)
    finally:
        # คืนค่าเดิมเสมอ!
        termios.tcsetattr(fd, termios.TCSADRAIN, old_attrs)
    
    return password

pwd = get_password()
print(f"\nEntered Password: {pwd}")

ผลลัพธ์

$ python3 example.py
Enter Password: 
Entered Password: my_password

กรณีใช้งานอื่นๆ

  • ตั้งค่า Baud Rate (Serial Communication)
  • Custom Line Discipline
  • Flow Control (Hardware/Software)
  • Terminal Resize Handling (SIGWINCH)

ความสัมพันธ์กับโมดูลอื่น

  • tty - High-level Wrapper (setraw, setcbreak)
  • pty - Pseudo Terminal
  • curses - Full-screen Terminal UI (ใช้ termios ภายใน)