首页 > 解决方案 > 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.

标签: pythonlinuxunixterminal

解决方案


根据评论中的@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>>> '

推荐阅读