python c api无法将任何模块导入到新创建的模块中
代码如下:python c api无法将任何模块导入到新创建的模块中,python,c,python-module,python-c-api,python-c-extension,Python,C,Python Module,Python C Api,Python C Extension,代码如下: python_script[] = "try:\n\timport sys\nexcept:\n\tprint\"cannot import sys\""; pNewMod = PyModule_New("mymod"); Py_Initialize(); pGlobal = PyDict_New(); pLocal = PyModule_GetDict(pNewMod); PyRun_String(python_script, Py_file_input, pGlobal, pLo
python_script[] = "try:\n\timport sys\nexcept:\n\tprint\"cannot import sys\"";
pNewMod = PyModule_New("mymod");
Py_Initialize();
pGlobal = PyDict_New();
pLocal = PyModule_GetDict(pNewMod);
PyRun_String(python_script, Py_file_input, pGlobal, pLocal);
我一直在import sys
中遇到异常,消息cannot import sys
被打印出来
此外:
PyRun_SimpleString("import sys");
PyRun_SimpleString("print sys.path");
很好。我无法将任何模块导入新创建的模块
为什么我不能导入任何模块?
我在这里遗漏了什么?以不同的方式解决了这个问题: 问题在于模块的
\u dict\u
属性是只读的
我正在为2.7.5使用python/CAPI。在使用PyModule\u New
后,没有为api中的导入执行\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
中的任何代码的设置。所以我用了不同的方法
我使用python代码而不是python/CAPI创建了一个模块。它提供将一些代码执行到mymod中的模块字典exec'import sys.\uuuu dict\uuuu
sys
导入提供了新创建的模块,以访问包含所有可用模块的sys.modules
。因此,当我进行另一次导入时,程序知道在哪里查找导入路径。这是代码
PyRun_SimpleString("import types,sys");
//create the new module in python
PyRun_SimpleString("mymod = types.ModuleType(\"mymod\")");
//add it to the sys modules so that it can be imported by other modules
PyRun_SimpleString("sys.modules[\"mymod\"] = mymod");
//import sys so that path will be available in mymod so that other/newly created modules can be imported
PyRun_SimpleString("exec 'import sys' in mymod.__dict__");
//import it to the current python interpreter
pNewMod=PyImport_Import(PyString_FromString("mymod"));
//get the dict of the new module
pLocal = PyModule_GetDict(pNewMod);
//run the code that you want to be available in the newly created module.
//python_script has the code that must be injected into the new module.
//all your imports will work fine from now on.
//Provided that you have created them before importing sys in to the new module
PyRun_String(python_script, Py_file_input, pGlobal, pLocal);