0

I need to run a Python script from c++, but I need also to pass it some variables. It can't be a function with parameters, because there are hundreds of variables, so the syntax would become too messy. I will post a simple example, analogue to my case. This is the Python script:

script.py

c = 10 * 5 + a
print(c)

And this is the calling code:

#include "Python.h"

int main()
{
    Py_Initialize();
    
    PyObject *pName = PyUnicode_FromString("script");
    PyObject *pModule = PyImport_Import(pName);;
    
    // Add something to set the cariable "a" in the script
    
    Py_Finalize();
}

Could you help with the code to add to set the variable "a" in the script?

4
  • Does this answer your question? Embedding python in C++: Assigning C++ and python variables Commented Oct 7, 2022 at 13:12
  • Hi @mugiseyebrows, this answer is doing the opposite: it is assigning to a c++ variable the value of a variable in the Python script. Instead I need to assign the value of a c++ variable to the script, before it is executed. Commented Oct 7, 2022 at 14:26
  • If the contents of your script are as you say, then wouldn't the code already be executed at import time? I think you want PyRun_FileExFlags instead with a custom globals dictionary. Commented Oct 7, 2022 at 14:43
  • @Botje, I think your comment makes sense. Can you help with the example code so I can test it? Commented Oct 7, 2022 at 15:02

1 Answer 1

2

The following will do the trick:

Py_Initialize();
    
PyObject *locals = PyDict_New();
PyObject *globals = PyDict_New();

PyDict_SetItemString(locals, "a", PyLong_FromLong(123));
PyDict_SetItemString(locals, "b", PyLong_FromLong(9));

PyRun_FileExFlags(fopen("script.py", "r"), "script.py", Py_file_input, globals, locals, 1, NULL);

Py_Finalize();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Botje, your solution is working, I added this line PyObject* val = PyDict_GetItemString(locals, "c"); and val has the correct value. The only unexpected issue is that the console is not printing the value of c as from the command in the last line of the Python script. Is it possible to get that output in the console?
The print shows up for me...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.