使用python pty伪终端进程发送命令并退出

问题描述:

使用python pty模块,我想使用stdin函数(如pty模块想要的那样)向终端仿真器发送一些命令,然后强制退出。我想到了类似的东西

Using python pty module, i want to send some commands to the terminal emulator, using a function as stdin (as pty module wants), and then force quitting. I thought about something like

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假装成为终端仿真器。

Firstly, the pty module does not allow you to communicate with the terminal emulator Python is running in. Instead, it allows Python to pretend to be a terminal emulator.

查看 pty.spawn()的源代码,它看起来像是旨在让生成的进程在运行时接管Python的stdin和stdout,这不是

Looking at the source-code of pty.spawn(), it looks like it is designed to let a spawned process take over Python's stdin and stdout while it runs, which is not what you want.

如果只想生成一个shell,向其发送命令,然后读取输出,则可能需要Python的 subprocess 模块(特别是,如果只有一个命令要运行,则 subprocess.Popen class' .communicate() 方法将很有帮助)。

If you just want to spawn a shell, send commands to it, and read the output, you probably want Python's subprocess module (in particular, if there's just one command you want to run, the subprocess.Popen class' .communicate() method will be helpful).

如果确实需要将子流程运行在pty而不是管道中,则可以可以使用 os.openpty()来分配一个主文件和一个从文件描述符。将从文件描述符用作子进程的stdin和stdout,然后将命令写入主文件描述符并从中读取响应。

If you really, really need the sub-process to be running in a pty instead of a pipe, you can use os.openpty() to allocate a master and a slave file descriptor. Use the slave file descriptor as the subprocess' stdin and stdout, then write your commands to the master file descriptor and read the responses back from it.