Calling Python script from C++ and using its output

前端 未结 2 1111
执笔经年
执笔经年 2020-11-30 03:34

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 file         


        
相关标签:
2条回答
  • 2020-11-30 03:49

    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 <Python.h>, 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)
  • 2020-11-30 03:54

    Try using POSIX's popen() instead of system(). It pipes stdin/stdout of child process to returned file handle.

    FILE* in = popen(command.c_str(), "r");
    
    fscanf(in, ... // or some other method of reading
    
    pclose(in);
    
    0 讨论(0)
提交回复
热议问题