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

标签 python c windows shell interfacing

有一个用 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/

相关文章:

python - 在启用 GPU 的 Windows 8 上安装 theano

python - Python 有 8KiB 字节长的文件 I/O 缓存吗?

python - 使用 django-social-auth 出现导入错误

python - 将 'any' 函数与列表压缩或生成器一起使用的正确语法

c - 简单的 30 个字符缓冲区 PIPE 打印不可打印的字符,不知道为什么

Cuda - 大数组初始化

windows - 如何在启动程序后关闭CMD

python - oauth2 获取访问 token 时的错误凭据响应

c - 首先验证文件格式,然后在 C 中检索所需信息

c++ - ld.exe : cannot find -ldwrite and -ldwmapi