gpt4 book ai didi

python - PyImport_Import 失败 - 返回 NULL

转载 作者:太空狗 更新时间:2023-10-29 23:27:52 37 4
gpt4 key购买 nike

首先,是的,我看到了thisthis ,但是他们没有解决我的问题/错误。


因此,我试图从 C/C++ 调用 Python 函数,但是当调用 PyImport_Import() 时,它返回 NULL

代码:

PyObject* fname = PyBytes_FromString("hello");
PyObject* module = PyImport_Import(fname);

hello 是我的 hello.py 文件,与可执行文件位于同一目录中。我不知道我的错误在哪里,有人可以指点我吗?

最佳答案

如果不了解有关系统设置方式和所涉及的 Python 文件内容的大量信息,就很难诊断您的问题。让 Python 运行时告诉您哪里出了问题要好得多。

documentation

PyObject* PyImport_ImportModule(const char *name)

...

Return a new reference to the imported module, or NULL with an exception set on failure

(强调我的)

exception handling documentation声明您可以调用 PyErr_Print() 将当前异常打印到 stderr。

所以要付诸实践:

PyObject* fname = PyBytes_FromString("hello");
PyObject* module = PyImport_Import(fname);
if (module == nullptr)
{
PyErr_Print();
std::exit(1);
}

这至少会让您开始找出错误。

为了将来的方便,您可能希望创建自己的 C++ 异常类来包装 Python 错误(并避免在代码中加入诸如调用 exit 之类的东西)。

关于python - PyImport_Import 失败 - 返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27469454/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com