2009-09-26 96 views
3

对不起,我不能在标题中更好地描述我的问题。Python - 同一行代码仅在第二次调用时才起作用?

我想学习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> 

我试图另一台机器上,如果一直失败。

+2

的问题是关于Python 2.6.2可再现的,Ubuntu 9.04的 – jfs 2009-09-26 14:00:33

+0

雪豹未确认,蟒蛇2.4.6手动安装。但有趣的问题。 – 2009-09-26 15:02:10

+0

这个工程使用python 2.6.2,Ubuntu 9.04的 – 2009-09-26 18:29:42

回答

4

minidom命名为一个模块,所以你应该需要

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

我不知道你是怎么得到第二parseString工作在我的蟒蛇未能在你的其他机器

+0

谢谢你,是的,我想访问xml.dom.Node第一次。*,所以我想从更高的层次来导入包。 我想这样做的方式是: import xml.dom import xml.dom.minidom ..这似乎工作,我猜那是正常的? – occhiso 2009-09-26 13:57:46

0

我做不到即使在第二次尝试时也可以使用代码(在Snow Leopard上使用Python 2.6.1)。 :-)但是,这里有一个版本可以帮我:

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

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

0

我可以在Ubuntu 9.04(python 2.6.2)上复制你的行为。如果你这样做python -v你可以看到第一个错误导致大量额外的进口。由于它不会发生在每个人身上,我只能假设Ubuntu/Debian已经为python添加了一些东西来自动加载模块。

仍然建议采取的措施是import xml.dom.minidom

7

问题在于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'> 
相关问题