Python 中的偽終端實用程式
偽終端的實用程式模組 pty 被定義為用來處理偽終端概念。使用這個模組我們可以啟動另一個程序,也可以使用程式來從控制終端讀寫。
這個模組非常注重平臺。為了執行這些操作我們應該使用 UNIX 系統。
為了使用 pty 模組,我們應該使用該模組進行匯入 −
import pty
pty 模組有以下幾個模組單元 −
方法 pty.fork()
這個方法用來將子控制終端連線到偽終端。這個方法返回 pid 和 fd。子程序得到 pid 0,但是 fd 是無效的。父程序的返回值是子程序的 pid,而 fd 儲存著子控制終端。
方法 pty.openpty()
這個方法用來開啟一個新的偽終端對。它返回主裝置和從裝置的檔案描述符。
方法 pty.spawn(argv[, master_read[, stdin_read]])
這個 spawn 程序用來將它的控制終端連線到當前程序的標準 IO。master_read 和 stdin_read 從檔案描述符中讀取。預設大小為 1024 位元組。
示例程式碼
import pty, os
def process_parent_child():
(process_id, fd) = pty.fork()
print("The Process ID for the Current process is: " + str(os.getpid()))
print("The Process ID for the Child process is: " + str(process_id))
process_parent_child()
master, slave = pty.openpty()
print('Name of the Master: ' + str(os.ttyname(master)))
print('Name of the Slave: ' + str(os.ttyname(slave)))
輸出
The Process ID for the Current process is: 12508 The Process ID for the Child process is: 12509 Name of the Master: /dev/ptmx Name of the Slave: /dev/pts/2
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP