抱歉,我无法在标题中更好地描述我的问题。
我正在尝试学习 Python,遇到了这种奇怪的行为,希望有人能向我解释一下。
我正在运行 Ubuntu 8.10 和 python 2.5.2
首先我导入 xml.dom
然后我创建一个 minidom 的实例(使用其完全限定的名称 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>
我在另一台机器上试过,如果一直失败。
最佳答案
问题出在 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'>
关于Python - 同一行代码仅在第二次调用时有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1481264/