【问题标题】:Import lxml module cause PyImport_ImportModule failed导入 lxml 模块导致 PyImport_ImportModule 失败
【发布时间】:2016-08-12 16:13:54
【问题描述】:

我编写了使用模块lxml的python测试代码。

我想在 C++ 中调用 foo

如果我添加from lxml import html,它将在步骤PyImport_ImportModule 中失败,但当我删除它时效果很好

Test.py

import os
import sys
import requests
from lxml import html     #it will cause failed

def foo():
    host = "http://www.baidu.com"
    s = requests.session()
    res = s.get(host)
    return res

c++代码:

Py_Initialize();
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
PyObject* pModule = PyImport_ImportModule("Test"); //failed
if (pModule == NULL || PyErr_Occurred()) 
{
   PyErr_Print();
}
PyObject* pDict = PyModule_GetDict(pModule);
PyObject *pFunHi = PyDict_GetItemString(pDict, "foo");
PyObject *ret = PyObject_CallFunction(pFunHi,NULL);
Py_DECREF(pFunHi);
Py_Finalize();

错误信息是:

Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\test\Test\Debug\Test.py", line 4, in <module>
from lxml import html
File "E:\python27\lib\site-packages\lxml\html\__init__.py", line 54, in <module>
from .. import etree
ImportError: DLL load failed: Unable to find the specified module。

如何正确使用lxml模块?

【问题讨论】:

  • 您应该检查是否pModule == NULL 或是否发生错误。如果有帮助,请查看我最近的answer
  • 您应该验证 lxml 是否已正确安装。

标签: python html c++ import lxml


【解决方案1】:

您的代码将崩溃

PyObject* pModule = PyImport_ImportModule("Test");
PyObject* pDict = PyModule_GetDict(pModule);  //will crash

如果pModule == NULL。您应该检查返回值,例如

if (pModule == NULL || PyErr_Occurred()) {
   PyErr_Print();
}

问题表明模块的文件名是 test.py 但在代码中模块名是 Test 即PyImport_ImportModule("Test")。大小写应该匹配。

验证 lxml 是否正确安装:

import lxml # does not fail if lxml has been partially installed
import lxml.etree # fails if C extension part of lxml has not been installed

如果后面导入失败,可能是lxml没有正确安装。

【讨论】:

  • **我评论你关注,我真的不知道如何在评论中使用markdown,我测试了很多次,它没有生效。 **
  • 我测试了“import lxml.etree”,失败了。 “导入lxml”没问题。我安装 lxml 使用 msi 包。也许正如你所说,lxml的c扩展部分还没有安装。我是python新手,我不知道c扩展部分是什么,以及如何确保安装了c扩展,你能给一些建议
  • 你能测试一下PyRun_SimpleString("sys.path.insert(0, './')");而不是sys.path.append会发生什么吗?
  • 奇怪,有段时间还好好的,突然就失败了……和之前一样显示错误,“DLL load failed”。我不知道发生了什么...
  • 嗨,我删除了从 pypi 下载的 lxml 3.6.0 msi,并从 lfd.uci.edu/~gohlke/pythonlibs/#lxml 安装了一个新的,版本 3.6.1。一切正常
【解决方案2】:

我解决了,是lxml安装程序的错。

我从https://pypi.python.org/pypi/lxml/3.6.0 (lxml-3.6.0.win32-py2.7.exe) 下载 3.6.0 版,因为它没有 3.6.1 版安装程序。它引起了我提到的问题。

所以我从http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml (lxml-3.6.1-cp27-cp27m-win32.whl) 下载了一个新的 whl 安装程序并更新了旧的。一切正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多