Python - 同一行代码仅在第二次调用时有效?

标签 python

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

我正在尝试学习 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/

相关文章:

python - 如何使用 re.split 作为 "slice at"函数进行拆分?

python - 在 Django 中管理静态文件

python - PyTorch 中的 .pt、.pth 和 .pwf 扩展名有什么区别?

python - 基于标签的重叠聚类(软聚类)

python - 导入错误 : No module named _smbus_cffi

python - 使用 dpkt 从 DNS 响应中读取 IP 地址和 TTL

python - openCV错误模块 'cv2.face'没有属性 'createEigenFaceRecognizer'

php - Django和PHP同时使用

python - 使用 python 导入我的数据库连接

python - 有没有办法从 scipy.stats.norm.fit 获取拟合参数的错误?