如何编写python代码来访问用C编写的程序的输入和输出?

tsr*_*guy 4 c python windows shell interfacing

有一个用C编写和编译的程序,从Unix shell输入典型数据; 另一方面,我正在使用Windows.

我需要从我用Python编写的代码的输出中向此程序发送输入.

这样做的最佳方法是什么?我已经读过pexpect,但不确定如何实现它; 任何人都可以解释这个问题的最佳方法吗?

Adr*_*son 6

我建议你使用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()
Run Code Online (Sandbox Code Playgroud)