UnboundLocalError:局部变量

时间:2012-12-24 12:44:04

标签: python urllib2

我的代码如下:

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

但是当我运行它时我得到了这个:

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

我尝试添加

global search_response

再次运行,我得到一个像这样的例外

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

2 个答案:

答案 0 :(得分:2)

如果您收到HTTPError,则表示您没有search_response个变量。所以这一行:

html_data = search_response.read()

引发错误,因为您试图访问未声明的search_response。我认为您应该像这样替换html_data = search_response.read()行:

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

答案 1 :(得分:0)

代码将转到下面代码中的exception,其中未设置search_response变量。

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

而不是使用pass,引发错误或将search_response变量设置为None

可能是这样的:

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

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