【问题标题】:Python import failed for PyQt4PyQt4 的 Python 导入失败
【发布时间】:2014-11-11 02:33:00
【问题描述】:

我正在尝试使用“imp”库来导出 PyQt4 的所有符号。使用内置的“import PyQt4.QtCore”是可以的,但是python的代码失败了。 我的测试基于 Mac。 在Windows上,好像如果你在QtCore目录下放一个“init.py”(空文件也可以), “导入 QtCore”会成功。 但在 Mac 上,由于某种未知原因,它失败了。 在 Cli 中:

bash-3.2# python
Python 2.7.5 (default, Mar  9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import PyQt4.QtCore as f
>>> print f.__file__
/Library/Python/2.7/site-packages/PyQt4/QtCore.so

但是,这种用法失败了。

bash-3.2# cd /Library/Python/2.7/site-packages/PyQt4/
bash-3.2# python
Python 2.7.5 (default, Mar  9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import QtCore
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
SystemError: dynamic module not initialized properly

谁能解释一下?

【问题讨论】:

    标签: python import pyqt4


    【解决方案1】:

    QtCore 不能直接导入python。 QtCore 存在于 PyQt4 库中。要访问 QtCore 类,您需要执行以下操作:

    Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] on win32
    Type "copyright", "credits" or "license()" for more information.
    >>> from PyQt4 import QtCore
    >>> 
    

    The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

    【讨论】:

    • 看来你在windows上运行导入,好吧,在windows上,“import QtCore”会失败,因为QtCore文件夹下没有“init.py”的地方,如果在文件夹下添加一个空的init.py,“import QtCore”就会成功。
    • 是的,没错。 init.py 文件表明该文件夹是库的根目录。 init.py 文件是使 Python 将目录视为包含包所必需的;这样做是为了防止具有通用名称(例如字符串)的目录无意中隐藏模块搜索路径中稍后出现的有效模块。在最简单的情况下,init.py 可以只是一个空文件,但它也可以执行包的初始化代码或设置 all 变量,稍后介绍。跨度>
    猜你喜欢
    • 2016-04-06
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 2011-04-29
    • 1970-01-01
    • 2015-02-16
    • 2013-12-13
    • 2019-02-14
    相关资源
    最近更新 更多