有个C++项目是读取配置参数文件并打印对应的结果,后来需要多次修改配置文件并运行,于是想到写个python脚本执行这一过程。
写一个测试项目,项目结构如下:
根目录
main.cpp // C++项目,从file.csv中读取配置文件并打印对应的结果
main.py // 多次循环,修改配置文件file.csv,运行.exe文件并打印
/build/
untitled.exe // C++生成的.exe文件
/data/
file.csv // C++读取的配置文件
配置文件file.csv如下
da, 4
db, 1.1
dc, 1.2
C++读取配置文件测试代码main.cpp如下
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
#include <iostream>#include <vector>#include <fstream>#include <sstream>#include <map>using namespace std;map<string, double> readKeyValuePairs(const string& fileName) { map<string, double> myMap; ifstream file(fileName); string line; while (getline(file, line)) { stringstream ss(line); string key; double value; getline(ss, key, ','); ss >> value; myMap[key] = value; } return myMap;}int main() { map<string, double> ans = readKeyValuePairs("../data/file.csv"); cout << ans.size() << "," << ans["da"]+ans["db"] << "; " << endl;} |
代码中注意配置文件与生成的.exe文件的相对位置。其中ans.size()用于判断是否正确读到了数据。
下面的代码用于多次修改配置文件,运行.exe文件并打印出.exe文件的运行结果。
|
1
2
3
4
5
6
7
8
9
10
|
import subprocessdef run_exe(exe_path): process = subprocess.Popen(exe_path, stdout=subprocess.PIPE, cwd='build') output, error = process.communicate() return output.decode('utf-8')for n in range(5): with open('data/file.csv', mode='w') as txtfile: print(f'da, {n}\ndb, 1.1\ndc, 1.2', file=txtfile) output = run_exe('build/untitled.exe') print(output, end='') |
其中cwd参数的详细解释见 Python cwd (1) -知乎,如果不设置这个参数,.exe文件的运行目录默认是根目录,也就是main.cpp所在的目录,需要用这个参数改成/build/目录,也就是untitled.exe所在的目录。
python代码运行结果如下
3,1.1;
3,2.1;
3,3.1;
3,4.1;
3,5.1;
下面的代码是chatGPT生成的python调用exe文件的原始代码
|
1
2
3
4
5
6
7
8
|
import subprocessdef run_exe(exe_path): process = subprocess.Popen(exe_path, stdout=subprocess.PIPE) output, error = process.communicate() return output.decode('utf-8')exe_path = 'your/exe_file.exe'output = run_exe(exe_path)print(output) |
原文链接:https://blog.csdn.net/qq_34288751/article/details/130536455
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END













暂无评论内容