gpt4 book ai didi

python - ElementTree/cElementTree 区别?

转载 作者:数据小太阳 更新时间:2023-10-29 02:06:53 25 4
gpt4 key购买 nike

我有一个小的 xml 解析 python 片段,它适用于 ElementTree,但不适用于 cElementTree。这是为什么?

#!/usr/bin/python3

import sys
import xml.etree.cElementTree as ET

tree = ET.parse(sys.stdin)

这引发了异常:

cElementTree.ParseError: no element found: line 1, column 0

当它这样调用时

echo "<a><b>c</b></a>" | ./xmltest.py

编辑:我刚刚注意到该片段在 python 2.7.2 中有效,但在 python 3.2.2 或 3.1.4 中无效,知道为什么吗?

更新:似乎在 python 3.3 中修复了

最佳答案

您遇到了最近在 Issue 14246 中记录的错误.在修复之前,Python 3 的一种解决方法是将 sys.stdin 更改为 byte 流而不是 string 流:

import sys
import xml.etree.cElementTree as ET

sys.stdin = sys.stdin.detach()
tree = ET.parse(sys.stdin)

关于python - ElementTree/cElementTree 区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9665558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com