python import失败_如何找出PyImportModule导入失败的原因?

本文介绍了在C程序中嵌入Python时遇到import模块失败的问题。当PyImport_ImportModule返回NULL时,文章探讨了如何诊断错误原因,特别是在外部环境中模块导入正常的情况下。通过检查sys.path、创建Python字符串和处理sys模块,帮助开发者识别和解决Python导入问题。
摘要由CSDN通过智能技术生成

我在一个嵌入Python(2.7.1)的C应用程序中有以下代码:{

PyObject *user_dict;

PyObject *user_func;

PyObject *result;

PyObject *header_tuple;

PyObject *original_recipients;

PyObject *working_recipients;

if (!Py_IsInitialized())

{

Py_Initialize();

}

if (!expy_exim_dict)

{

PyObject *module = Py_InitModule(expy_exim_module, expy_exim_methods); /* Borrowed reference */

Py_INCREF(module); /* convert to New reference */

expy_exim_dict = PyModule_GetDict(module); /* Borrowed reference */

Py_INCREF(expy_exim_dict); /* convert to New reference */

}

if (!expy_user_module)

{

if (expy_path_add)

{

PyObject *sys_module;

PyObject *sys_dict;

PyObject *sys_path;

PyObject *add_value;

sys_module = PyImport_ImportModule("sys"); /* New Reference */

if (!sys_module)

{

PyErr_Clear();

*return_text = "Internal error, can't import Python sys module";

log_write(0, LOG_REJECT, "Couldn't import Python 'sys' module");

return PYTHON_FAILURE_RETURN;

}

sys_dict = PyModule_GetDict(sys_module); /* Borrowed Reference, never fails */

sys_path = PyMapping_GetItemString(sys_dict, "path"); /* New reference */

if (!sys_path || (!PyList_Check(sys_path)))

{

PyErr_Clear(); /* in case sys_path was NULL, harmless otherwise */

*return_text = "Internal error, sys.path doesn't exist or isn't a list";

log_write(0, LOG_REJECT, "expy: Python sys.path doesn't exist or isn't a list");

return PYTHON_FAILURE_RETURN;

}

add_value = PyString_FromString(expy_path_add); /* New reference */

if (!add_value)

{

PyErr_Clear();

log_write(0, LOG_PANIC, "expy: Failed to create Python string from [%s]", expy_path_add);

return PYTHON_FAILURE_RETURN;

}

if (PyList_append(sys_path, add_value))

{

PyErr_Clear();

log_write(0, LOG_PANIC, "expy: Failed to append [%s] to Python sys.path", expy_path_add);

}

Py_DECREF(add_value);

Py_DECREF(sys_path);

Py_DECREF(sys_module);

}

expy_user_module = PyImport_ImportModule(expy_scan_module); /* New Reference */

if (!expy_user_module)

{

PyErr_Clear();

/* Handle error */

}

}

当PyImport_ImportModule失败时,它返回NULL。如何找出为什么导入失败?(例如,导入模块作品时,请在嵌入之外查找)。在

(这段代码是py-exim-localscan的一部分,我想添加更多关于罕见情况下失败发生的信息)。在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值