【问题标题】:Python - Same line of code only works the second time it called?Python - 同一行代码仅在第二次调用时有效?
【发布时间】:2009-09-26 13:49:42
【问题描述】:

抱歉,我无法在标题中更好地描述我的问题。

我正在尝试学习 Python,遇到了这种奇怪的行为,希望有人能向我解释一下。

我正在运行 Ubuntu 8.10 和 python 2.5.2

首先我导入 xml.dom
然后我创建一个 minidom 的实例(使用它的完全 qaulified 名称 xml.dom.minidom)
这失败了,但是如果我再次运行同一行,它就可以了! 见下文:

$> python
Python 2.5.2 (r252:60911, Oct  5 2008, 19:29:17) 
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import xml.dom
>>> xml.dom.minidom.parseString("<xml><item/></xml>")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'minidom'
>>> xml.dom.minidom.parseString("<xml><item/></xml>")
<xml.dom.minidom.Document instance at 0x7fd914e42fc8>

我在另一台机器上尝试过,如果一直失败。

【问题讨论】:

  • 该问题在 Python 2.6.2、Ubuntu 9.04 上可重现
  • 未在雪豹上确认,手动安装了 python 2.4.6。然而有趣的问题。
  • 这是第一次使用 python 2.6.2, Ubuntu 9.04

标签: python


【解决方案1】:

问题在于apport_python_hook.apport_excepthook() 的副作用是它导入了xml.dom.minidom

没有apport_except_hook

>>> import sys
>>> sys.excepthook = sys.__excepthook__
>>> import xml.dom
>>> xml.dom.minidom
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'minidom'
>>> xml.dom.minidom
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'minidom'
>>>  

apport_except_hook:

>>> import apport_python_hook
>>> apport_python_hook.install()
>>> xml.dom.minidom
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'minidom'
>>> xml.dom.minidom
<module 'xml.dom.minidom' from '../lib/python2.6/xml/dom/minidom.pyc'>

【讨论】:

    【解决方案2】:

    minidom 是一个模块,所以你应该需要

    import xml.dom.minidom
    xml.dom.minidom.parseString("<xml><item/></xml>")
    

    我不知道你是如何让第二个 parseString 工作的,它在我的 python 上像在你的另一台机器上一样失败

    【讨论】:

    • 谢谢,是的,我想访问 xml.dom.Node.* 所以我想从更高级别导入包。我想这样做的方法是: import xml.dom import xml.dom.minidom .. 这似乎有效,我想这很正常?
    【解决方案3】:

    即使在第二次尝试(在 Snow Leopard 上使用 Python 2.6.1)时,我也无法让您的代码正常工作。 :-) 但是,这里有一个对我有用的版本:

    >>> from xml.dom.minidom import parseString
    >>> parseString("<xml><item/></xml>")
    <xml.dom.minidom.Document instance at 0x100539830>
    

    就个人而言,我更喜欢这种导入方式。它往往会减少冗长的代码。

    【讨论】:

      【解决方案4】:

      我可以在 Ubuntu 9.04 (python 2.6.2) 上复制您的行为。如果您执行python -v,您会看到第一个错误会导致大量额外的导入。因为不是每个人都会发生这种情况,所以我只能假设 Ubuntu/Debian 已经在 python 中添加了一些东西来自动加载模块。

      建议的操作仍然是import xml.dom.minidom

      【讨论】:

        猜你喜欢
        • 2014-07-11
        • 1970-01-01
        • 1970-01-01
        • 2010-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-01
        • 1970-01-01
        相关资源
        最近更新 更多