Python UnboundLocalError:局部变量
我的代码如下:Python UnboundLocalError:局部变量,python,urllib2,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: p
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
然后再次运行,我会遇到这样的异常
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
回溯(最近一次呼叫最后一次):
文件“G:\MyProjects\python\lfi\u tmp.py”,第78行,在中,如果您得到HTTPError
您没有search\u响应
变量。所以这一行:
html_data = search_response.read()
引发错误,因为您正试图访问未声明的搜索\u响应
。我认为您应该替换html\u data=search\u 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
代码将进入下面代码中的异常
,其中未设置search\u response
变量
try:
search_response = urllib2.urlopen(search_request)
except urllib2.HTTPError:
pass
html_data = search_response.read()
print html_data
不要使用pass
,而是引发错误或将search\u 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:
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