Using urlopen in Python2 and Python3

Ned Batchelder ned at nedbatchelder.com
Mon Aug 24 13:37:50 EDT 2015


On Monday, August 24, 2015 at 1:14:20 PM UTC-4, Cecil Westerhof wrote:
> In Python2 urlopen is part of urllib, but in Python3 it is part of
> urllib.request. I solved this by the following code:
> ========================================================================
> from platform   import python_version
> 
> if python_version()[0] < '3':
>     from urllib         import urlopen
> else:
>     from urllib.request import urlopen

A less specific technique is:

    try:
        from urllib import urlopen
    except ImportError:
        from urllib.request import urlopen

Even better, the six package, which helps with 2/3 compatibility,
provides this:

    from six.moves.urllib.request import urlopen

which works on both 2 and 3.

--Ned.



More information about the Python-list mailing list