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

发布于 2024-12-24 19:55:31 字数 438 浏览 2 评论 0原文

使用 python pty 模块,我想使用 stdin 函数(如 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)

“谢谢”之类的事情

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)

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你曾走过我的故事 2024-12-31 19:55:31

首先,pty 模块不允许您与运行 Python 的终端仿真器进行通信。相反,它允许 Python 假装成终端仿真器。

查看 pty.spawn() 的源代码,看起来它的设计目的是让派生进程在运行时接管 Python 的 stdin 和 stdout,这不是您想要的。

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

如果您确实需要子进程在 pty 而不是管道中运行,则可以使用 os.openpty() 来分配主文件描述符和从文件描述符。使用从属文件描述符作为子进程的标准输入和标准输出,然后将命令写入主文件描述符并从中读回响应。

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.

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.

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).

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文