在Python3中使用cElementTree

2024-10-01 15:39:42 发布

您现在位置:Python中文网/ 问答频道 /正文

cElementTree是xmlapiElementTree的快速C实现。在python2中,您将显式地加载它(将其别名为ElementTree),但在the Python 3 docs中,我读到了以下内容:

Changed in version 3.3: This module will use a fast implementation whenever available. The xml.etree.cElementTree module is deprecated.

实际上,xml.etree.cElementTree.py现在只是从xml.etree.ElementTree导入。问题是:如何获得“快速实施”?如何判断它是否“可用”,如果出于某种原因它没有与python一起分发,我从哪里得到它?在

在我的程序中对ElementTree的反思表明我得到了python版本。在ElementTree.py中,我没有发现任何指向C版本的钩子。什么时候,如何发挥作用?ElementTree文档没有提供任何线索,也没有在google和stackoverflow上进行快速搜索。在


Tags: theinpy版本docsversionxmlthis
1条回答
网友
1楼 · 发布于 2024-10-01 15:39:42

来自“What's New in Python 3.3”文档:

The xml.etree.ElementTree module now imports its C accelerator by default; there is no longer a need to explicitly import xml.etree.cElementTree (this module stays for backwards compatibility, but is now deprecated). In addition, the iter family of methods of Element has been optimized (rewritten in C). The module’s documentation has also been greatly improved with added examples and a more detailed reference.

虽然它看起来好像没有发生,但导入是无声的。您将在ElelementTree.py中找到一段代码

# Import the C accelerators
try:
    # Element, SubElement, ParseError, TreeBuilder, XMLParser
    from _elementtree import *
except ImportError:
    pass
else:
    # Overwrite 'ElementTree.parse' and 'iterparse' to use the C XMLParser

    class ElementTree(ElementTree):
       ...

似乎没有一个简单的方法来验证是否导入了C模块,但我认为您可以接受它是导入的。如果你真的很担心(我个人也不会担心),那么你可以在那里打一个print来检查。在

相关问题 更多 >

    热门问题