【问题标题】:How to automate interactive console applications in Python?如何在 Python 中自动化交互式控制台应用程序?
【发布时间】:2017-01-25 11:31:33
【问题描述】:

我想通过 Python 中的脚本来控制正在运行的进程/程序。 我有一个程序“linphonec”(您可以安装:apt-get install linphonec)。 我的任务是:

  1. 运行linphonec(我目前正在使用子进程)
  2. linphonec 运行时,它有许多命令来控制它,我想例如使用proxy listlinphonec 中的命令)。

简单流程:

test@ubuntu$ > linphonec
linphonec > proxy list

我该怎么做?

【问题讨论】:

  • 寻找 pexpect 模块
  • 试试 man linphonec 或 linphonec --help
  • 我更改了标题以更清楚地解决问题。我对您的文本进行了一些重新格式化,以便于阅读。
  • 好吧,你是对的。重新格式化后更容易阅读。谢谢。

标签: python linux shell subprocess linphone


【解决方案1】:

其实有两种沟通方式:

使用myprogram.py | linphonec 运行您的程序,将您print 的所有内容传递给linphonec

在构造函数中通过 keywrod-args 使用 subprocess.Popensubprocess.PIPE 用于 stdin(也可能是 stdout 和 stderr),然后将 communicate 用于单个命令或使用 stdinstdout (stderr)作为文件

import subprocess
p=subprocess.Popen("linphonec",
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    universal_newlines=True) #this is for text communication
p.stdin.write("proxy list\n")
result_first_line=p.stdout.readline()

【讨论】:

  • 谢谢!我测试了你的第一个通知和预期模块。
猜你喜欢
  • 2012-08-01
  • 1970-01-01
  • 2020-07-01
  • 1970-01-01
  • 2012-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-15
相关资源
最近更新 更多