Why am I getting an AttributeError when trying to print out
Asked Answered
M

3

13

I am learning about urllib2 by following this tutorial http://docs.python.org/howto/urllib2.html#urlerror Running the code below yields a different outcome from the tutorial

import urllib2

req = urllib2.Request('http://www.pretend-o-server.org')
try:
    urllib2.urlopen(req)
except urllib2.URLError, e:
    print e.reason

Python interpreter spits this back

Traceback (most recent call last):
  File "urlerror.py", line 8, in <module>
    print e.reason
AttributeError: 'HTTPError' object has no attribute 'reason'

How come this is happening?

UPDATE

When I try to print out the code attribute it works fine

import urllib2

req = urllib2.Request('http://www.pretend-o-server.org')
try:
    urllib2.urlopen(req)
except urllib2.URLError, e:
    print e.code
Machado answered 26/9, 2011 at 12:10 Comment(2)
Do you get the same error code if instead print e.reason you put print e.code?Hankhanke
@Nick Ok now I am getting the AttributeError no matter which URL I pass in and no matter how I import and use urllib2 (and its methods). So everything is working predictably. When I do print e.code I get 404. @agf I'm using 2.6.5 and by the way, how did you get [Errno 11004] getaddrinfo failed. I swear I was getting that same message early today, I took a break, came back, ran the same code again and just get the original AttributeError. I'm thinking ghost in the machine but perhaps I am missing something.Machado
M
1

The reason I got the AttributeError was because I was using OpenDNS. Apparently even when you pass in a bogus URL, OpenDNS treats it like it exists. So after switching to Googles DNS server, I am getting the expected result which is:

[Errno -2] Name or service not known

Also I should mention the traceback I got for running this code which is everything excluding try and except

from urllib2 import Request, urlopen, URLError, HTTPError

req = Request('http://www.pretend_server.com')
    urlopen(req)

is this

Traceback (most recent call last):
  File "urlerror.py", line 5, in <module>
    urlopen(req)
  File "/usr/lib/python2.6/urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.6/urllib2.py", line 397, in open
    response = meth(req, response)
  File "/usr/lib/python2.6/urllib2.py", line 510, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.6/urllib2.py", line 435, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.6/urllib2.py", line 369, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.6/urllib2.py", line 518, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 404: Not Found

which a kind gentle(wo)man? from IRC #python told me was highly strange and then asked if I was using OpenDNS to which I replied yes. So they suggested I switch it to Google's which I proceeded to do.

Machado answered 26/9, 2011 at 22:1 Comment(0)
H
8

Depending on the error type, the object e may or may not carry that attribute.

In the link you provided there is a more complete example:

Number 2

from urllib2 import Request, urlopen, URLError
req = Request(someurl)
try:
    response = urlopen(req)
except URLError, e:
    if hasattr(e, 'reason'): # <--
        print 'We failed to reach a server.'
        print 'Reason: ', e.reason
    elif hasattr(e, 'code'): # <--
        print 'The server couldn\'t fulfill the request.'
        print 'Error code: ', e.code
else:
    # everything is fine
Hankhanke answered 26/9, 2011 at 12:34 Comment(4)
right on, I saw this example and just changed the way I imported urllib2 methods and they way I call them (dropped the urllib2 prefix) and the first example works now. See update.Machado
@s3z: your code snippets are equivalent. It could be a different error. Change the first snippet to print e.code to see if they indeed differ.Hankhanke
Nick, Ahh. I realize that I was testing a different URL before. Please check my edited update. Sorry for the confusion.Machado
Testing for attributes on the error object? Really? This must be the worst object oriented design choice ever. ThanksVeneering
L
4

Because there is no such attribute. Try:

print str(e)

and you will get nice:

HTTP Error 404: Not Found
Lvov answered 26/9, 2011 at 12:16 Comment(4)
Right but how come it works for the author in the tutorial? How come he gets (4, 'getaddrinfo failed')?Machado
I tried it, and I get [Errno 11004] getaddrinfo failed so this is definitely not a complete answer.Gasometer
What OS and python version do you have?Deflower
Michał, I am using Python 2.6.5Machado
M
1

The reason I got the AttributeError was because I was using OpenDNS. Apparently even when you pass in a bogus URL, OpenDNS treats it like it exists. So after switching to Googles DNS server, I am getting the expected result which is:

[Errno -2] Name or service not known

Also I should mention the traceback I got for running this code which is everything excluding try and except

from urllib2 import Request, urlopen, URLError, HTTPError

req = Request('http://www.pretend_server.com')
    urlopen(req)

is this

Traceback (most recent call last):
  File "urlerror.py", line 5, in <module>
    urlopen(req)
  File "/usr/lib/python2.6/urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.6/urllib2.py", line 397, in open
    response = meth(req, response)
  File "/usr/lib/python2.6/urllib2.py", line 510, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.6/urllib2.py", line 435, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.6/urllib2.py", line 369, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.6/urllib2.py", line 518, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 404: Not Found

which a kind gentle(wo)man? from IRC #python told me was highly strange and then asked if I was using OpenDNS to which I replied yes. So they suggested I switch it to Google's which I proceeded to do.

Machado answered 26/9, 2011 at 22:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.