【问题标题】:How to write python code to access input and output from a program written in C?如何编写python代码来访问用C编写的程序的输入和输出?
【发布时间】:2012-12-28 21:21:41
【问题描述】:

有一个用 C 语言编写和编译的程序,典型的数据输入来自 Unix shell;另一方面,我使用的是 Windows。

我需要从我自己用 Python 编写的代码的输出中向这个程序发送输入。

执行此操作的最佳方法是什么?我读过pexpect,但不确定如何实现它;谁能解释解决这个问题的最佳方法?

【问题讨论】:

  • 这是一个 C 还是 C++ 问题?
  • 按照你描述的方式,很难判断这是否是一个过滤程序(如grepsort),它只接受一个标准输入流并写入一个标准输出流,或者它是否是一个带有提示和响应的交互式 CLI 程序(如 python 本身)。如果是前者,subprocess.communicate 就是你所需要的;如果是后者,pexpect 是一个不错的选择,但除非您提出比“如何实现它”更具体的问题,否则没人能真正帮助您。
  • 因此 C 中的程序将是 python 中的“模块”。我想通过从 python 发送输入、获取 C 程序的输出并在我自己的 python 代码中使用它来访问这些函数。这有意义吗?

标签: python c windows shell interfacing


【解决方案1】:

我建议您使用 python subprocess 模块。

它是os.popen() 函数调用的替代品,它允许在通过管道与其标准输入/输出/错误流交互的同时执行程序。

示例使用:

import subprocess

process = subprocess.Popen("test.exe", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
input,output = process.stdin,process.stdout

input.write("hello world !")
print(output.read().decode('latin1'))

input.close()
output.close()
status = process.wait()

【讨论】:

  • 如果输出是有界的,它应该写成output = process.communicate("hello world !")[0]@abarnert 说。阅读有关直接使用 .stdin、.stdout in the docs 的警告。在某些情况下,您还需要stderr=PIPElatin1 字符编码不是最佳选择。它接受任何输入,因此它隐藏了错误。
  • 另外,有时您可能需要stderr=subprocess.STDOUT
【解决方案2】:

如果您不需要处理回答交互式问题和提示,请不要理会pexpect,只需按照 Adrien Plisson 的建议使用 subprocess.communicate

但是,如果您确实需要pexpect,最好的入门方法是查看其主页上的examples,然后在获得处理你到底需要做什么。

【讨论】:

    猜你喜欢
    • 2017-02-19
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    相关资源
    最近更新 更多