c调用python脚本如何获取结果,从C ++调用Python的脚本,并使用其输出

I want to call a python script from C++ and wish to use the output .csv file generated by this script back into C++. I tried this in main():

std::string filename = "/home/abc/xyz/script.py";

std::string command = "python ";

command += filename;

system(command.c_str());

This does call and execute the python script.

EDIT_2 The 'print' commands in the python are being executed...things are being printed on the screen when the script is called. So far so good. But! it is not creating the .csv file (part of the same script). like: i had a training.csv file with 100 entries. I called the python script, with little changes to the script so that the trainig.csv file now should contain only 50 entries instead of 100. Its overwritten. But, no such thing happening. Rest of the commands in script (print, etc) are working perfectly.

The training.csv file is to be read with C++ normally using fstream and getline...

Any idea how to do it?

EDIT using linux

Thanks!

解决方案

Here is a solution to embed the execution of your python module from within your C++ application. It's not better or worst than forking/executing your python script through a system call, it just is a different way to do it. Whether it is best or not depend on your context and usage.

Some time ago I have coded a way to load python modules as plugins to a C++ application, here's the interesting part.

Basically, you need to #include , then Py_Initialize() to start your python interpreter.

Then you do import sys, using : PyRun_SimpleString("import sys");, and you can load your plugin by doing PyRun_SimpleString('sys.path.append("path/to/my/module/")').

To exchange values between C++ and Python, things get harder, you have to to transform all your C++ objects into python objects (starting line 69 in my script).

Then you can call your function using PyObject_Call_Object(...), using all the python objects you created as arguments.

You get the return value, and transforms all those values in C++ objects. And don't forget the memory management in all that!

To end your python interpreter, a simple call to Py_Finalize().

It really looks harder than it is really, but you have to be really careful doing this, because it could lead to leaks, security issues etc..

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值