在C/C++与Python之间实现通信的方式有很多,以下是一些常见的方法:
1. 使用系统调用(subprocess):
可以使用Python的subprocess
模块执行C/C++程序,并通过标准输入输出进行通信。
在Python中:
import subprocess
result = subprocess.run(['your_cpp_program'], input='input_data', text=True, capture_output=True)
print(result.stdout)
在C/C++程序中,你可以使用cin
读取Python传递的输入,并使用cout
输出结果。
2. 使用共享文件:
C/C++程序可以将结果写入一个文件,Python再读取该文件。
在C/C++中:
#include <fstream>
using namespace std;
int main() {
ofstream output("output.txt");
output << "Hello from C/C++!";
output.close();
return 0;
}
在Python中:
with o