2009-09-26 45 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'> 
相關問題