我正在寻找有关如何组合两个代码片段的建议,以便它们可以同时使用python 2和3.目标是使其"整洁",理想情况下将其保持为一行并限制任何if/else/try /除了结构.
对于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
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())))
Jon-Eric.. 10
这正是six
为此创建的.它是一个允许你的代码同时使用Python 2和3的库.(不要让"库"吓到你,它只是一个.py文件,使它很容易集成/打包.)
您不必使用内置urllib
模块,而是使用六个版本,它会自动重定向到Python 2和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://pythonhosted.org/six/#module-six.moves.urllib.request
这正是six
为此创建的.它是一个允许你的代码同时使用Python 2和3的库.(不要让"库"吓到你,它只是一个.py文件,使它很容易集成/打包.)
您不必使用内置urllib
模块,而是使用六个版本,它会自动重定向到Python 2和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://pythonhosted.org/six/#module-six.moves.urllib.request
如果你不想要额外的依赖,你可以简单地使用一个try
except
块来导入同一个别名下的模块...:
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())))