发送命令并退出使用python pty伪终端进程
问题描述:
使用python pty模块,我想发送一些命令到终端模拟器,使用函数作为标准输入(如pty模块想要的),然后强制退出。我想过像发送命令并退出使用python pty伪终端进程
import pty
cmnds = ['exit\n', 'ls -al\n']
# Command to send. I try exiting as last command, but it doesn't works.
def r(fd):
if cmnds:
cmnds.pop()
# It seems is not executing sent commands ('ls -al\n')
else:
# Can i quit here? Can i return EOF?
pass
pty.spawn('/bin/sh', r)
谢谢
答
首先,pty
模块不允许你用Python,在运行终端仿真程序进行通信。相反,它允许Python假装是一个终端仿真器。
看看pty.spawn()
的源代码,它看起来像是设计用来让一个衍生进程在运行时接管Python的标准输入和标准输出,这不是你想要的。
如果你只是想产生一个外壳,将命令发送到它,并读取输出,您可能需要Python的subprocess
模块(特别是,如果有要运行的subprocess.Popen
类的.communicate()
方法只是一个命令有帮助)。
如果你确实需要子进程在pty中运行而不是管道,那么可以使用os.openpty()
来分配主文件和从文件描述符。使用从属文件描述符作为子进程的stdin和stdout,然后将命令写入主文件描述符并从中读取响应。
你可能想要研究pexpect,它是专为这种事情而设计的:http://www.noah.org/wiki/pexpect – 2012-01-03 11:40:23
我只有pty可用 – Emilio 2012-01-03 13:33:05
我只是试过,不能使它工作,但从文档我得到的功能是与输出交互不接收参数列表 – 2012-01-04 03:58:35