Python嵌入:PyImport不是从当前目录导入

2024-10-01 09:37:59 发布

您现在位置:Python中文网/ 问答频道 /正文

使用下一行

pModule = PyImport_Import(pName);

仅从当前目录加载模块。

但我想从别的地方装些什么?有什么好办法吗?

PyRun_SimpleString("import sys\nsys.path.append('<dir>')"); 很好,但是有点难看-我在找更好的方法

谢谢!


Tags: 模块pathimport地方dirsyspyrunappend
2条回答

有一个很好的方法,因为这是它经常与网站包装的方式。

import sys
sys.path.append(directory) # sys.path is a list of all directories to import from

或者你用

os.cwd(directory) # change the working directory

在进口之前。

另一种方式是丑陋的:

import types, sys
m = types.ModuleType('module')
sys.modules['module'] = m
exec open('file').read() in m.__dict__ # python3

也许你要求一个C函数来完成你的工作,但我不知道。

我在http://realmike.org/blog/2012/07/08/embedding-python-tutorial-part-1/找到了我想要的答案

Normally, when importing a module, Python tries to find the module file next to the importing module (the module that contains the import statement). Python then tries the directories in “sys.path”. The current working directory is usually not considered. In our case, the import is performed via the API, so there is no importing module in whose directory Python could search for “shout_filter.py”. The plug-in is also not on “sys.path”. One way of enabling Python to find the plug-in is to add the current working directory to the module search path by doing the equivalent of “sys.path.append(‘.’)” via the API.

Py_Initialize();
PyObject* sysPath = PySys_GetObject((char*)"path");
PyObject* programName = PyString_FromString(SplitFilename(argv[1]).c_str());
PyList_Append(sysPath, programName);
Py_DECREF(programName);

SplitFilename是我为获取目录而编写的函数。

相关问题 更多 >