在PythonC API中创建模块时,如何包含UuBuild_U类

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

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

我试图使用Python 3.5 C API来执行一些代码,其中包括构造类。具体来说:

class MyClass:
    def test(self):
        print('test')

MyClass().test()

我的问题是它的错误如下:

^{pr2}$

因此,我需要我的模块包含__build_class__,但我不确定如何(我猜我也会错过使用Python时默认得到的其他东西)-有没有方法在我的模块中包含所有这些内置的东西?在

以下是我目前为止的代码:

#include <Python.h>

int main(void)
{
    int ret = 0;
    PyObject *pValue, *pModule, *pGlobal, *pLocal;

    Py_Initialize();

    pGlobal = PyDict_New();
    pModule = PyModule_New("mymod");
    pLocal = PyModule_GetDict(pModule);

    pValue = PyRun_String(
        "class MyClass:\n\tdef test(self):\n\t\tprint('test')\n\nMyClass().test()",
        Py_file_input,
        pGlobal,
        pLocal);

    if (pValue == NULL) {
        if (PyErr_Occurred()) {
            PyErr_Print();
        }
        ret = 1;
    } else {
        Py_DECREF(pValue);
    }

    Py_Finalize();

    return ret;
}

所以pValue是{},它在调用{}。在


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

他们(至少)有两种方法可以解决这个问题。。。在

方法1

而不是:

pGlobal = PyDict_New();

您可以导入__main__模块并获得它的globals字典,如下所示:

^{pr2}$

这样描述:

BUT PyEval_GetGlobals will return null it it is not called from within Python. This will never be the case when extending Python, but when Python is embedded, it may happen. This is because PyRun_* define the global scope, so if you're not somehow inside a PyRun_ thing (e.g. module called from python called from embedder), there are no globals.

In an embedded-python situation, if you decide that all of your PyRun_* calls are going to use __main__ as the global namespace, PyModule_GetDict(PyImport_AddModule("__main__")) will do it.

这是我从这个问题得到的。在

方式2

或者作为另一种选择,我个人更喜欢导入主模块(找到了here),您可以这样做,用内置的东西填充您创建的新字典,其中包括__build_class__

pGlobal = PyDict_New();
PyDict_SetItemString(pGlobal, "__builtins__", PyEval_GetBuiltins());

相关问题 更多 >

    热门问题