Skip to main content
 首页 » 编程设计

python之与 python 上的交互式 shell 脚本交互

2024年10月24日9shangdawei

我在 Windows 上有一个交互式 shell 应用程序。 我想编写一个 python 脚本,它将命令发送到该 shell 应用程序并读回响应。 但是我想以交互方式进行,即我希望 shell 应用程序在 python 脚本运行时一直运行。

我试过了

self.m_process subprocess.Popen(path_to_shell_app,shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,universal_newlines=True) 

然后使用标准输入和标准输出发送和接收数据。 似乎正在打开 shell 应用程序,但我无法与之通信。

我做错了什么?

请您参考如下方法:

有一个专门为此构建的模块:pexpect .要使用,import pexpect,然后使用process = pexpect.spawn(myprogram)创建新的子进程,并使用process.expect(mystring) 或 process.expect_exact(mystring) 搜索提示或获取响应。 process.send(myinput) 和process.sendline(myinput) 用于向子进程发送信息。