Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execute .py file from c++

Tags:

c++

python

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?

like image 301
Shahriar Avatar asked Jun 14 '26 21:06

Shahriar


1 Answers

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.

like image 75
Wintermute Avatar answered Jun 17 '26 11:06

Wintermute



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!