Embedding Python in C: Having problems importing local modules

余生颓废 提交于 2019-12-07 05:37:14

问题


I need to run Python scripts within a C-based app. I am able to import standard modules from the Python libraries i.e.:

PyRun_SimpleString("import sys")

But when I try to import a local module can

PyRun_SimpleString("import can")

returns the error message:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: No module named can

When I type the command import can in IPython, the system is able to find it.

How can I link my app with can? I've tried setting PYTHONPATH to my working directory.


回答1:


Embedding the Python library does not add '' to sys.path like the interactive interpreter does. Use PySys_SetPath() to add the appropriate directory.

Oh hey, look what I found.




回答2:


I found this to work much more robustly,

PyObject *sys = PyImport_ImportModule("sys");
PyObject *path = PyObject_GetAttrString(sys, "path");
PyList_Append(path, PyUnicode_FromString("."));


来源:https://stackoverflow.com/questions/2917645/embedding-python-in-c-having-problems-importing-local-modules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!