A clear way to make urllib work with python 2 and 3

I am looking for suggestions on how to combine two code snippets so that they work with both python 2 and 3. The goal is to make it “neat”, ideally keeping it on one line and limiting any if / else / try / except constructs.

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

For 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())))
+5
source share
2 answers

This is exactly what it was created for . This is a library designed so that your code can work with both Python 2 and 3. (Don't let the "library" scare you, it is intentionally only one .py file, so it is very easy to integrate / package.) six

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://six.readthedocs.io/#module-six.moves.urllib.request

+10

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

Source: https://habr.com/ru/post/1546044/


All Articles