pythoncapi无法将任何模块导入到新创建的modu中

2024-09-27 20:17:20 发布

您现在位置:Python中文网/ 问答频道 /正文

代码如下:

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}$

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

为什么我不能导入任何模块? 我错过了什么?在


Tags: 模块代码pyimportnewsysscripttry
1条回答
网友
1楼 · 发布于 2024-09-27 20:17:20

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

我使用的是python/capi for 2.7.5。在使用PyModule_New之后,没有设置在__dict__中执行任何代码,以便在api中导入。所以我用了另一种方法。在

我使用python代码而不是python/capi创建了一个模块。它提供了在模块字典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);

相关问题 更多 >

    热门问题