【问题标题】:How to run executable from python and pass it arguments asked for?如何从 python 运行可执行文件并传递要求的参数?
【发布时间】:2014-03-10 08:28:05
【问题描述】:

我不知道如何从 python 运行可执行文件,然后传递它一个一个请求的命令。我在这里找到的所有示例都是通过在调用可执行文件时直接传递参数来完成的。但是我拥有的可执行文件需要“用户输入”。它一一要求值。

例子:

subprocess.call(grid.exe)
>What grid you want create?: grid.grd
>Is it nice grid?: yes
>Is it really nice grid?: not really
>Grid created

【问题讨论】:

  • 您可以将命令序列写入文件,并让可执行文件从该文件中获取输入。
  • @Jayanth 谢谢。我知道如何在 python 中创建文本文件并在其中写入行,所以为什么不呢。但是我如何让那个可执行文件读取那个输入(文本)文件呢?

标签: python command subprocess


【解决方案1】:

您可以使用subprocessPopen.communicate 方法:

import subprocess

def create_grid(*commands):
    process = subprocess.Popen(
        ['grid.exe'],
        stdout=subprocess.PIPE,
        stdin=subprocess.PIPE,
        stderr=subprocess.PIPE)

    process.communicate('\n'.join(commands) + '\n')

if __name__ == '__main__':
    create_grid('grid.grd', 'yes', 'not really')

“通信”方法本质上是传入输入,就好像您正在输入一样。确保以换行符结束每一行输入。

如果您希望grid.exe 的输出显示在控制台上,请将create_grid 修改为如下所示:

def create_grid(*commands):
    process = subprocess.Popen(
        ['grid.exe'],
        stdin=subprocess.PIPE)

    process.communicate('\n'.join(commands) + '\n')

警告:我尚未完全测试我的解决方案,因此无法确认它们在每种情况下都有效。

【讨论】:

  • 谢谢。我已经复制了这个,只是将参数更改为更多,但出现错误:self.stdin.write(input) TypeError: 'str' does not support the buffer interface
  • @Miro -- 你碰巧在使用 Python 3 吗?如果是这样,您可能需要先cast the string to bytes,然后再致电communicate。 (再一次,我不能 100% 确定这是否是实际问题)
  • 是的,Windows 7 上的 PortablePython_3.2.5.1。我会试试的,谢谢。
  • 太棒了,它有效!非常感谢。对于 Python 3,我所要做的就是将最后一行写为 process.communicate(bytes('\n'.join(commands) + '\n', 'UTF-8'))
猜你喜欢
  • 1970-01-01
  • 2011-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-06
  • 1970-01-01
  • 1970-01-01
  • 2018-12-10
相关资源
最近更新 更多