2012-12-24 80 views
1

我的代码如下:UnboundLocalError:局部变量

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

如果你正在得到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 
+0

好非常非常好! – robert

0

的代码下面的代码,其中search_response变量没有设置要去exception

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 
相关问题