开发者

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

开发者 https://www.devze.com 2023-03-08 22:59 出处:网络
PyRun_String(\"random.randint(1,10)\", Py_eval_input, globals, globals); returns error with: Traceback (most recent call last):
PyRun_String("random.randint(1,10)", Py_eval_input, globals, globals);

returns 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 guess this is not the way to get it work. What is the co开发者_如何学运维rrect way? Thank you!


PyImport_ImportModule returns the imported value. You need to save it in globals under the name random. In summary:

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

but don't forget to also check the result of the import in case it throws an exception.

0

精彩评论

暂无评论...
验证码 换一张
取 消