python c api无法将任何模块导入新创建的模块

时间:2013-06-08 15:43:59

标签: 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, pLocal);

我一直在import sys收到异常,并且会打印消息cannot import sys

另外:

PyRun_SimpleString("import sys");
PyRun_SimpleString("print sys.path");

工作正常。我无法将任何模块导入新创建的模块中。

为什么我无法导入任何模块? 我在这里错过了什么?

1 个答案:

答案 0 :(得分:0)

以不同的方式解决了这个问题: 问题是模块的__dict__属性是只读的。

我使用的是2.7.5的python / c api。使用PyModule_New后,没有配置为api中的导入__dict__执行任何代码。所以我采用了不同的方法。

我使用python代码而不是python / c api创建了一个模块。其中规定将一些代码执行到模块字典exec 'import sys' in mymod.__dict__中。

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);
相关问题