Python C API: how to get PyRun_String with Py_eval_input to use imported modules?

PyRun_String("random.randint(1,10)", Py_eval_input, globals, globals);

returns an error with:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
NameError: name 'random' is not defined

earlier in the code, I did:

PyImport_ImportModule("random");

I think this is not a way to make it work. What is the right way? Thank!

+3
source share
1 answer

PyImport_ImportModulereturns the imported value. You need to save it in globalsunder a name random. In short:

PyMapping_SetItemString(globals, "random", PyImport_ImportModule("random"));

but be sure to also check the import result if it throws an exception.

+2
source

All Articles