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

Pseudo-terminal Utilities ใน Python (โมดูล pty)

โมดูล pty จัดการ Pseudo-Terminal (PTY) ใช้เริ่ม Process ใหม่และอ่าน/เขียนผ่าน Controlling Terminal เหมาะสำหรับ Automation, Testing, Terminal Emulators

ทำงานได้เฉพาะ UNIX/Linux

import pty


เมธอดหลัก

pty.fork()

Fork Process และเชื่อม Child ไปยัง PTY ใหม่

  • คืนค่า: (pid, fd)
  • Child: pid=0, fd=invalid
  • Parent: pid=Child PID, fd=Master PTY FD

pty.openpty()

เปิด PTY Pair ใหม่ (Master/Slave)

  • คืนค่า: (master_fd, slave_fd)
  • Master: ควบคุม Terminal
  • Slave: ทำงานเหมือน Terminal จริง

pty.spawn(argv[, master_read[, stdin_read]])

Spawn Process และเชื่อม Controlling Terminal กับ Std I/O

  • argv: Command + Arguments
  • master_read, stdin_read: Callback อ่านข้อมูล (Default 1024 bytes)

โค้ดตัวอย่าง

import pty, os

# 1. Fork with PTY
pid, fd = pty.fork()
print(f"Current PID: {os.getpid()}")
print(f"Child PID: {pid}")

if pid == 0:
    # Child Process
    os.execvp('bash', ['bash'])
else:
    # Parent - อ่าน/เขียนผ่าน fd
    pass

# 2. Open PTY Pair
master, slave = pty.openpty()
print(f"Master: {os.ttyname(master)}")   # /dev/ptmx
print(f"Slave: {os.ttyname(slave)}")     # /dev/pts/2

ผลลัพธ์

Current PID: 12508
Child PID: 12509
Master: /dev/ptmx
Slave: /dev/pts/2

การประยุกต์ใช้จริง

  • Terminal Emulators: xterm, gnome-terminal, tmux ใช้ PTY
  • Automation: รัน Interactive Program (ssh, sudo, passwd) แบบ Headless
  • Testing: ทดสอบ CLI Tools ที่ต้องการ TTY
  • Debuggers: GDB, PDB ใช้ PTY สำหรับ Debug Target

ตัวอย่าง: รัน Interactive Command

import pty, sys

def read_from_fd(fd):
    return os.read(fd, 1024)

# รันคำสั่งที่ต้องการ TTY (เช่น sudo)
pty.spawn(['sudo', 'ls', '/root'], master_read=read_from_fd)

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

  • tty - Terminal Control (Raw/Cbreak Mode)
  • termios - POSIX TTY I/O Control
  • os - Low-level FD Operations
  • subprocess - ใช้ pty ภายในสำหรับ stdin=subprocess.PIPE + universal_newlines