python - pexpect 获取应用信息
问题描述
我正在使用 pexpect 从 linux 主机运行 nano,我正在尝试找到一种从 pexpect 获取信息的方法,以便我可以在其他地方重建 nano(或 vi 或任何终端应用程序)。
所以像:
p = pexpect.spawn('/bin/bash')
p.sendline('nano cheese')
#Get the tty information for the nano/vi/whatever UI#
我本质上想转发信息(信息是应用程序 UI)而不直接与之交互,这可能吗?
解决方案
通常,处理这种情况的方法是 .interact(),它将子进程置于当前进程中。但是,听起来您不想交互,而是想从父进程控制子进程。
像这样的东西应该工作:
import pexpect
p = pexpect.spawn('nano cheese')
output = []
while p.isalive():
output.append(p.read_nonblocking(100000))
#Conditionals about what is in output could be put here.
#You can also tell pexpect to block until it finds specific strings, with .expect()
p.sendline(input().encode())
试图遵循应该在“nano”中输入的内容,我认为你想做这样的事情:
y #answer yes to first question
^X #exit nano
n #no, don't save
<enter> #anything sent should end the process here.
这假设“nano”没有询问意外的东西,比如已经有一个文件或其他东西等。您可以使用 p.expect 根据输出中显示的字符串启动某些操作。打印输出以查看“nano”发送给您的内容。
print(output)