使用 python pty 伪终端进程发送命令并退出
使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,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, thesubprocess.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.