os.openpty() tạo một cặp pseudo-terminal (master, slave) — dùng cho terminal emulator, SSH, expect-like automation.
Ví dụ
import os
master_fd, slave_fd = os.openpty()
print(f"Master fd: {master_fd}")
print(f"Slave fd: {slave_fd}")
# Tên device của slave
slave_name = os.ttyname(slave_fd)
print(f"Slave tty: {slave_name}") # /dev/pts/3 (Linux)
Kết quả mẫu
Master fd: 3 Slave fd: 4 Slave tty: /dev/pts/3
Ứng dụng
- Chạy subprocess với terminal giả (để chương trình nghĩ đang chạy interactive).
- Implement terminal emulator, SSH server, expect-like tool.
- Test chương trình interactive tự động.
Ví dụ chạy command trong pty
import os, subprocess master, slave = os.openpty() proc = subprocess.Popen(['bash'], stdin=slave, stdout=slave, stderr=slave) os.close(slave) # đóng slave ở parent # Gửi lệnh qua master os.write(master, b'ls -la\n') os.write(master, b'exit\n') # Đọc output output = os.read(master, 4096) print(output.decode())