Search code examples
pythonpython-requestsurllib2six

python six library for 2 and 3 compatibility for requests


How can I use the python six library for 2 and 3 compatibility on the foll. code sample:

import urllib.request

wp = urllib.request.urlopen("http://google.com")
pw = wp.read()
print(pw)

-- EDIT I tried this:

from six.moves.urllib.request import urlopen, urlretrieve
import six.moves.urllib.request as Request

request = Request('http://google.com')

but get this error:

TypeError: 'Module_six_moves_urllib_request' object is not callable

Solution

  • You've almost had it:

    from six.moves.urllib.request import urlopen
    
    wp = urlopen("http://google.com")
    pw = wp.read()
    print(pw)
    

    Or if you wanted to addess urllib directly as in the first attempt, use from six.moves import urllib.