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

更新于: 30-7-2019

1 千次+ 查看

开启你的 事业

通过完成课程获得认证

开始
广告
© . All rights reserved.