代码如下:
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
得到一个异常,消息{
同时:
^{pr2}$工作正常。我无法将任何模块导入到新创建的模块中。在
为什么我不能导入任何模块? 我错过了什么?在
以不同的方式解决这个问题: 问题是模块的
__dict__
属性是只读的。在我使用的是python/capi for 2.7.5。在使用
PyModule_New
之后,没有设置在__dict__
中执行任何代码,以便在api中导入。所以我用了另一种方法。在我使用python代码而不是python/capi创建了一个模块。它提供了在模块字典
exec 'import sys' in mymod.__dict__
中执行某些代码的规定。在sys
导入提供新创建的模块,以访问拥有所有可用模块的sys.modules
。所以当我执行另一个导入时,程序知道在哪里查找导入的路径。这是密码。在相关问题 更多 >
编程相关推荐