7

使用下一行

pModule = PyImport_Import(pName);

仅从当前目录加载模块。

但是我想从其他地方加载什么?有没有一种巧妙的方法可以做到这一点?

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

谢谢!

4

2 回答 2

15

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

通常,在导入模块时,Python 会尝试在导入模块(包含导入语句的模块)旁边找到模块文件。然后 Python 会尝试“sys.path”中的目录。通常不考虑当前工作目录。在我们的例子中,导入是通过 API 执行的,因此 Python 可以在其目录中搜索“shout_filter.py”的导入模块不存在。该插件也不在“sys.path”上。使 Python 能够找到插件的一种方法是通过 API 执行相当于“sys.path.append('.')”的操作,将当前工作目录添加到模块搜索路径中。

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是我为获取目录而编写的函数。

于 2014-01-22T12:54:30.830 回答
-1

有一个好方法,因为这是站点包经常使用的方法。

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 函数来完成你的工作,但我不知道。

于 2014-01-22T10:24:19.013 回答