【问题标题】:python c api not able to import any module into the newly created modulepython c api无法将任何模块导入新创建的模块
【发布时间】:2013-06-04 18:24:48
【问题描述】:

代码如下:

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");

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

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

【问题讨论】:

    标签: python c python-module python-c-api python-c-extension


    【解决方案1】:

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

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

    我使用 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-28
      • 2012-01-09
      • 2021-07-04
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 2013-08-01
      相关资源
      最近更新 更多