【问题标题】:Python: Run command for another software in terminalPython:在终端中运行另一个软件的命令
【发布时间】:2021-11-20 22:31:11
【问题描述】:

我正在使用我实验室开发的软件,我们称之为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执行的。

【问题讨论】:

  • 使用pexpect
  • 或者使用subprocess.Popen(),然后将command_for_cool_software写入stdin管道。
  • @Barmar 谢谢!!我对subprocess 解决方案非常感兴趣。它会是什么样子?
  • @Barmar 也许是subprocess.Popen(["cool_software"], stdin="command_for_cool_software")
  • 如果这是唯一的输入,那就行了。

标签: python linux unix terminal


【解决方案1】:

根据 cmets 的 @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('.+')

这是我得到的:

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>>> '

【讨论】:

  • 谢谢!! expected output 会是输出的名称吗?
  • 来自文档:spawn 类是 Pexpect 系统更强大的接口。您可以使用它来生成子程序,然后通过发送输入和期望响应(等待子程序输出中的模式)与它进行交互。
  • @Euler_Salter,对不起,我误读了你的问题。我以为你在问expect() 做了什么。关于你的问题,我编辑了我的答案。希望这会有所帮助
猜你喜欢
  • 2020-03-02
  • 2018-12-28
  • 2021-08-16
  • 1970-01-01
  • 2014-03-08
  • 2017-02-07
  • 1970-01-01
  • 1970-01-01
  • 2018-09-23
相关资源
最近更新 更多