AttributeError: 'URLError' object has no attribute 'code'

I am working on a little script which transcribes WAV files located in a local directory using a local host running SpeechRecognition ( ). However, for some reason I'm getting an odd error of AttributeError: 'URLError' object has no attribute 'code'.

Here is a trimmed down traceback:

Traceback (most recent call last):
  File "C:\Python34\lib\urllib\", line 1182, in do_open
    h.request(req.get_method(), req.selector,, headers)
  File "C:\Python34\lib\http\", line 1088, in request
    self._send_request(method, url, body, headers)
  File "C:\Python34\lib\", line 494, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  File "C:\Python34\lib\", line 533, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python34\lib\urllib\", line 1210, in http_open
    return self.do_open(http.client.HTTPConnection, req)
  File "C:\Python34\lib\urllib\", line 1184, in do_open
    raise URLError(err)
urllib.error.URLError: <urlopen error [Errno 11001] getaddrinfo failed>

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/William/Documents/FlashBulb/userMedia/", line 86, in do_POST
  File "C:/Users/William/Documents/FlashBulb/userMedia/", line 29, in recognize
    print("Google Speech Recognition thinks you said " + r.recognize_google(audio))
  File "C:\Python34\lib\site-packages\speech_recognition\", line 408, in recognize_google
    raise RequestError("recognition connection failed: {0}".format(getattr(e, "reason", "status {0}".format(e.code)))) # use getattr to be compatible with Python 2.6
AttributeError: 'URLError' object has no attribute 'code'
Exception happened during processing of request from ('', 62409)

And here is the script:


import time
from http.server import BaseHTTPRequestHandler, HTTPServer
import os
import cgi
import speech_recognition as sr

HOST_NAME = 'localhost'
ASSETS_DIR = 'assets'

if not os.path.exists(ASSETS_DIR):

def recognize(wav_file):
    print("Recognizing ", wav_file)
    r = sr.Recognizer()
    r.energy_threshold = 350
    r.pause_threshold = 10.0
    with sr.WavFile(wav_file) as source:
        audio = r.record(source)

        # for testing purposes, we're just using the default API key
        # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
        # instead of `r.recognize_google(audio)`
        print("Google Speech Recognition thinks you said " + r.recognize_google(audio))

    except sr.UnknownValueError as e:
        print("Google Speech Recognition could not understand audio")
    except sr.RequestError as e:
        print("Could not request results from Google Speech Recognition service; {0}".format(e))

class MyHandler(BaseHTTPRequestHandler):
    previous_wav = ""

    def do_GET(self):

        if self.path == "/":
            self.path = "/index.html"

            sendReply = False
            if self.path.endswith(".html"):
                mimetype = 'text/html'
                sendReply = True
            if self.path.endswith(".js"):
                mimetype = 'application/javascript'
                sendReply = True

            if sendReply:
                # Open the static file requested and send it
                f = open(os.path.join(os.curdir + os.sep + self.path))
                self.send_header('Content-type', mimetype)
                self.wfile.write(bytes(, 'utf-8'))

        except IOError:
            self.send_error(404, 'File Not Found: %s' % self.path)

    def do_POST(self):

        if self.path == '/upload':
            form = cgi.FieldStorage(

            filename = form.getvalue("fname").strip()
            data = form['data']
            output_file = os.path.join(os.curdir, ASSETS_DIR, filename)
            open(output_file, "wb").write(data)
            if str(output_file) != MyHandler.previous_wav:
            MyHandler.previous_wav = str(output_file)

if __name__ == '__main__':

    server_class = HTTPServer
    httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)
    print(time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER))
    except KeyboardInterrupt:
    print(time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER))

Open in new window

I would of ran a set trace  but I'm not sure how to do that since it would interrupt the post process. I haven't seen an issue like this before so I'm not sure exactly what is happening. Any help would be awesome!
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Joseph GanSystem AdminCommented:
Try something after this:     except sr.UnknownValueError as e:

return_code = e.code
         if hasattr(e, 'reason'):
             #HTTPError and URLError all have reason attribute.
             print 'We failed to reach a server.'
             print 'Reason: ', e.reason
             print 'code: ', e.code
             return_html = e.reason
         elif hasattr(e, 'code'):
             #Only HTTPError has code attribute.
             print 'The server couldn\'t fulfill the request.'
             print 'Error code: ', e.code
         # everything is fine

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
WillNy3Author Commented:
Thanks for your help. I still have no ******* clue what happened. This morning it just worked, exact same code, no changes, nothing. I didn't even add in your additional error handling. Gotta love debugging -.-
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.