python - Python:在终端中运行另一个软件的命令
问题描述
我正在使用我实验室开发的软件,我们称之为cool_software
。当我cool_software
在终端上输入时,基本上我会得到一个新的提示cool_software >
,我可以从终端向这个软件输入命令。
现在我想在 Python 中自动执行此操作,但是我不确定如何将cool_software
命令传递给它。这是我的 MWE:
import os
os.system(`cool_software`)
os.system(`command_for_cool_software`)
上面代码的问题command_for_cool_software
是在通常的 unix shell 中执行,它不是由cool_software
.
解决方案
根据评论中的@Barmar 建议,使用pexpect非常简洁。从文档中:
spawn 类是 Pexpect 系统更强大的接口。您可以使用它来生成子程序,然后通过发送输入和期望响应(等待子程序输出中的模式)与它进行交互。
这是一个使用python
提示作为示例的工作示例:
import pexpect
child = pexpect.spawn("python") # mimcs running $python
child.sendline('print("hello")') # >>> print("hello")
child.expect("hello") # expects hello
print(child.after) # prints "hello"
child.close()
在您的情况下,它将是这样的:
import pexpect
child = pexpect.spawn("cool_software")
child.sendline(command_for_cool_software)
child.expect(expected_output) # catch the expected output
print(child.after)
child.close()
笔记
child.expect()
只符合您的预期。如果您不期望任何东西并且想要获得自开始以来的所有输出spawn
,那么您可以使用child.expect('.+')
which 将匹配所有内容。
这就是我得到的:
b'Python 3.8.10 (default, Jun 2 2021, 10:49:15) \r\n[GCC 9.4.0] on linux\r\nType "help", "copyright", "credits" or "license" for more information.\r\n>>> print("hello")\r\nhello\r\n>>> '
推荐阅读
- azure-storage - 将 VSAM 文件从 Mainframe 一次性迁移到 Cloud Azure
- css - 不同浏览器上的滚动条行为
- html - 显示约束到父元素的子元素
- reactjs - 在 useEffect (Redux Saga) 中使用 Dispatch 时获得无限 API 调用
- ipad - 如何建立一个与我的第 8 代 iPad 具有相同分辨率的网站?
- sql-server - 如何在 SQL 中获得明智的产品总和
- c++ - 默认初始化和值初始化的含义?
- entity-framework-core - 扩展 Identity Server 4 的配置和操作数据上下文
- php - PHP 错误记录:为什么西里尔字符在日志文件中进行十六进制编码以及如何防止它?
- java - 使用kotlin或java的json对象内的数组内的Json对象