Using urlopen in Python2 and Python3

Cecil Westerhof Cecil at decebal.nl
Mon Aug 24 20:21:21 CEST 2015


On Monday 24 Aug 2015 19:37 CEST, Ned Batchelder wrote:

> 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.

Implemented. Thanks.


At the moment I also use:
========================================================================
from __future__     import division, print_function
.
.
.
# To work with Python2 the flush is a seperate statement
print('It took {0:.5f} seconds'.format(end_time - start_time))
sys.stdout.flush()
========================================================================

Would it be better to use:
========================================================================
from six import print_
.
.
.
print_('It took {0:.5f} seconds'.format(end_time - start_time), flush = true)
========================================================================

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof


More information about the Python-list mailing list