【问题标题】:Wrapping an interactive command line application in a Python script在 Python 脚本中包装交互式命令行应用程序
【发布时间】:2010-12-06 17:53:20
【问题描述】:

我有兴趣通过 Python 调用控制交互式 CLI 应用程序。

我想在最基本的层面上,我需要一个 Python 脚本来在主机操作系统上启动一个 CLI 应用程序。将标准输入中的任何内容通过管道传输到 CLI 应用程序,然后将 CLI 应用程序的任何输出通过管道传输到标准输出。

从这个基础上,对输入和输出进行一些处理应该是相当简单的。

老实说,我可能只需要一个关于该技术称为什么的指针。我不知道我需要搜索什么。

【问题讨论】:

    标签: python command-line


    【解决方案1】:

    PExpect 是否符合您的需求?

    【讨论】:

      【解决方案2】:

      也许你想要来自Subprocess (MOTW) 的东西。

      我使用这样的代码来调用 shell:

      from subprocess import Popen, PIPE
      
      ## shell out, prompt
      def shell(args, input=''):
          ''' uses subprocess pipes to call out to the shell.
      
          args:  args to the command
          input:  stdin
      
          returns stdout, stderr
          '''
          p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
          stdout, stderr = p.communicate(input=input)
          return stdout, stderr
      

      【讨论】:

      • +1 因为subprocess 库是 Python 标准库的一部分,并且可以完成工作。
      • 不仅如此,使用 Popen,您还可以使用参数列表作为参数!
      猜你喜欢
      • 2011-06-30
      • 1970-01-01
      • 2012-07-03
      • 1970-01-01
      • 1970-01-01
      • 2021-03-13
      • 2012-07-12
      • 2018-03-16
      • 1970-01-01
      相关资源
      最近更新 更多