使urllib与python2和python3协同工作的一种简便方法

2024-06-30 07:36:16 发布

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

我正在寻找关于如何组合这两个代码片段的建议,以便它们可以同时使用python2和python3。其目标是使其“整洁”,理想情况下保持在一行,并限制任何if/else/try/except结构。在

对于python 3.x

   import xml.etree.ElementTree as ET, urllib.request, gzip, io
   url = "https://github.com/OpenExoplanetCatalogue/oec_gzip/raw/master/systems.xml.gz"
   oec = ET.parse(gzip.GzipFile(fileobj=io.BytesIO(urllib.request.urlopen(url).read())))

对于python 2.x

^{pr2}$

Tags: 代码iourl目标request情况xmlurllib
2条回答

这正是创建^{}的目的。它是一个允许代码同时使用Python2和3的库。(不要让“library”吓到你,它故意只是一个.py文件,以便非常容易地集成/打包。)

不使用内置的urllib模块,而是使用six的版本,它会自动重定向到python2和3中的内置模块。在

您的代码如下所示:

import xml.etree.ElementTree as ET, gzip, io
from six.moves.urllib.request import urlopen
url = "https://github.com/OpenExoplanetCatalogue/oec_gzip/raw/master/systems.xml.gz"
oec = ET.parse(gzip.GzipFile(fileobj=io.BytesIO(urlopen(url).read())))

请参见:https://six.readthedocs.io/#module-six.moves.urllib.request

如果不需要额外的依赖项,可以使用tryexcept块在同一别名下导入任意一个模块…:

try:
    import urllib.request as urlrequest
except ImportError:
    import urllib as urlrequest

url = "https://github.com/OpenExoplanetCatalogue/oec_gzip/raw/master/systems.xml.gz"
oec = ET.parse(gzip.GzipFile(fileobj=io.BytesIO(urlrequest.urlopen(url).read())))

相关问题 更多 >