robert
robert

Reputation: 25

UnboundLocalError: local variable

My code is the following:

search_request = urllib2.Request(url,data=tmp_file_name,headers={'X-Requested-With':'WoMenShi888XMLHttpRequestWin'})
#print search_request.get_method()
try:
    search_response = urllib2.urlopen(search_request)
except urllib2.HTTPError:
    pass
html_data = search_response.read()
print html_data

but when I run it I get this:

Traceback (most recent call last):
  File "G:\MyProjects\python\lfi_tmp.py", line 78, in <module>
    print hello_lfi()
  File "G:\MyProjects\python\lfi_tmp.py", line 70, in hello_lfi
    html_data = search_response.read()
UnboundLocalError: local variable 'search_response' referenced before assignment

I tried adding

global search_response

and run again, I get an exception like this

Traceback (most recent call last):
  File "G:\MyProjects\python\lfi_tmp.py", line 78, in <modul
    print hello_lfi()
  File "G:\MyProjects\python\lfi_tmp.py", line 70, in hello_
    html_data = search_response.read()
NameError: global name 'search_response' is not defined

Upvotes: 1

Views: 700

Answers (2)

Amyth
Amyth

Reputation: 32959

The code is going to the exception in the code below, where search_response variable is not set.

try:
    search_response = urllib2.urlopen(search_request)
except urllib2.HTTPError:
    pass
html_data = search_response.read()
print html_data

instead of using pass, raise an Error or set search_response variable to None.

maybe something like:

try:
    search_response = urllib2.urlopen(search_request)
except urllib2.HTTPError:
    raise SomeError
html_data = search_response.read()
print html_data

or

try:
    search_response = urllib2.urlopen(search_request)
except urllib2.HTTPError:
    search_response = None
if html_data:
    html_data = search_response.read()
    print html_data
else:
    # Do something else

Upvotes: 0

alexvassel
alexvassel

Reputation: 10740

If you are getting HTTPError you have no search_response variable. So this line:

html_data = search_response.read()

raises your error, because you are attempting to access search_response that wasn't declared. I think that you should replace the html_data = search_response.read() line like this for example:

search_request = urllib2.Request(url,data=tmp_file_name,headers={'X-Requested-With':'WoMenShi888XMLHttpRequestWin'})
    #print search_request.get_method()
try:
    search_response = urllib2.urlopen(search_request)
    html_data = search_response.read()  #New here
except urllib2.HTTPError:
    html_data = "error" #And here

print html_data

Upvotes: 2

Related Questions