有一个用 C 编写和编译的程序,典型的数据输入来自 Unix shell;另一方面,我正在使用 Windows。
我需要从我自己用 Python 编写的代码的输出向这个程序发送输入。
执行此操作的最佳方法是什么?我读过有关 pexpect
的内容,但不确定如何实现它;任何人都可以解释解决此问题的最佳方法吗?
最佳答案
我推荐你使用 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()
关于python - 如何编写 python 代码来访问用 C 编写的程序的输入和输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14326528/