3

I'm working with c++. I need to execute a python script with condition

int main()
{
    if(op==1)
    {
        RUN("MUL.py"); // execute MUL.py script
    }
    else
    {
        RUN("DIV.py"); // execute DIV.py script
    }

    return 0;
}

I can do like below:

Py_Initialize();
PyRun_SimpleString(code);
Py_Finalize();

Here, I have to make a string. Then I need to run.

But, I don't want to do this. I already have a .py file. All I need to run that file.

something like: py_run(MUL.py)

My python code will do some large calculation for me. That will write the answer in a file. I will read that answer from that file in my c++ code.

How can I do this?

Shahriar
  • 13,460
  • 8
  • 78
  • 95

1 Answers1

7

There's the PyRun_SimpleFile function family for that. For example:

FILE *fd = fopen("MUL.py", "r");
PyRun_SimpleFileEx(fd, "MUL.py", 1); // last parameter == 1 means to close the
                                     // file before returning.

See also the documentation.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
Wintermute
  • 42,983
  • 5
  • 77
  • 80
  • 1
    See also http://stackoverflow.com/questions/3654652/why-does-the-python-c-api-crash-on-pyrun-simplefile – John Zwinck Feb 03 '15 at 14:20
  • 1
    I'm guessing your compiler doesn't have the python directories in its include and linker path. Add the output of `python-config --cflags` to your compiler flags and the output of `python-config --ldflags` to your linker flags. – Wintermute Feb 03 '15 at 15:24
  • :( `compiler flags` and `linker flags` are unknown to me. where should I find these? I'm using visual studio in windows – Shahriar Feb 03 '15 at 15:32
  • See https://msdn.microsoft.com/en-us/library/ee855621.aspx . You have to put the directories with the python headers in the include path and the directory with the python libraries in the linker path. Then you have to add the library -- probably python.lib or python2.7.lib or so, but I've never linked to python under Windows -- to the additional linker input in the project options (under "Linker"). Also take note that `` expects to be `#include`d before any system headers. – Wintermute Feb 03 '15 at 15:43