gpt4 book ai didi

Python 嵌入 : PyImport_Import not from the current directory

转载 作者:太空狗 更新时间:2023-10-30 00:32:51 24 4
gpt4 key购买 nike

使用下一行

pModule = PyImport_Import(pName);

只从当前目录加载模块。

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

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

谢谢!

最佳答案

刚刚在 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 是我写的获取目录的函数。

关于Python 嵌入 : PyImport_Import not from the current directory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21279913/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com