使用Python2和Python3创建urllib的简洁方法

使用Python2和Python3创建urllib的简洁方法,python,python-3.x,urllib,Python,Python 3.x,Urllib,我正在寻找关于如何组合这两个代码片段的建议,以便它们能够与Python2和Python3一起工作。目标是使其“整洁”,理想情况下保持一行,并限制任何if/else/try/except构造 对于Python3.x import xml.etree.ElementTree as ET, urllib.request, gzip, io url = "https://github.com/OpenExoplanetCatalogue/oec_gzip/raw/master/systems

我正在寻找关于如何组合这两个代码片段的建议,以便它们能够与Python2和Python3一起工作。目标是使其“整洁”,理想情况下保持一行,并限制任何if/else/try/except构造

对于Python3.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())))
对于Python2.x

  import xml.etree.ElementTree as ET, urllib, gzip, io
  url = "https://github.com/OpenExoplanetCatalogue/oec_gzip/raw/master/systems.xml.gz"
  oec = ET.parse(gzip.GzipFile(fileobj=io.BytesIO(urllib.urlopen(url).read())))
这正是创建的目的。它是一个库,允许您的代码同时使用Python2和Python3。(不要让“library”吓到你,它只是一个.py文件,以便很容易集成/打包。)

不要使用内置的
urllib
模块,而是使用six的版本,它会自动重定向到Python 2和Python 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())))

请参阅:

如果您不需要额外的依赖项,您只需使用
try
块(除了
块)即可在同一别名下导入任一模块…:

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())))

urllib导入将有所不同。一个答案是:使用
请求
。或者,运行py2/py3的测试,并将适当的urllib urlopen作为urlopen导入。您可能会看到
six
,它包含一个布尔值,用于测试您是否在Python3或Python2中:
six。PY3
很好的建议:我没有意识到
six
可以做到这一点。我在其他方面也使用过它。任何人在请求上使用urllib的唯一原因是为了避免任何依赖关系,包括六个。