UnboundLocalError: local variable ‘respon1’ referenced before assignment
V1:
def main():
time1='2024-08-01 08:00:00' # 开始 08:00:00
time2='2024-09-01 07:59:59' # 结束 07:59:00
begintime=str_data_to_num(time1)
endtime=str_data_to_num(time2)
ss=get_grafana_login()
print('登录成功')
try:
for pf_num in [1]:
dd=get_peaknum(ss,begintime,endtime,pf_num) # ss为登录后的cookie
respon=clean_data(dd,pf_num)
respon1 = respon[respon.alluser !=0] # 过滤空值
# to_sql(respon,'zbj_peaknum',pf_num)
print(respon1.time.max())
print(pf_num,time1,time2,respon1.shape[0])
except:
print(pf_num,'取数失败')
return respon1
修改方法1:
在except块中,可以给respon1赋一个默认值,比如None,这样在出现异常时,函数也能有一个明确的返回值,而不会因为找不到respon1的赋值而报错
def main():
time1='2024-08-01 08:00:00' # 开始 08:00:00
time2='2024-09-01 07:59:59' # 结束 07:59:00
begintime=str_data_to_num(time1)
endtime=str_data_to_num(time2)
ss=get_grafana_login()
print('登录成功')
try:
for pf_num in [1]:
dd=get_peaknum(ss,begintime,endtime,pf_num)
respon=clean_data(dd,pf_num)
respon1 = respon[respon.alluser!=0] # 过滤空值
# to_sql(respon,'zbj_peaknum',pf_num)
print(respon1.time.max())
print(pf_num,time1,time2,respon1.shape[0])
return respon1
except:
print(pf_num,'取数失败')
return None
修改方法2:
将可能出现异常的部分单独封装成一个函数,在这个函数中处理异常并返回合适的值,然后在main函数中调用这个函数来获取结果,这样可以使代码结构更清晰,也更容易处理错误情况。
def get_respon1(ss, begintime, endtime, pf_num):
try:
dd = get_peaknum(ss, begintime, endtime, pf_num)
respon = clean_data(dd, pf_num)
return respon[respon.alluser!= 0]
except:
print(pf_num, '取数失败')
return None
def main():
# MINJUN Begin
time1 = '2024-08-01 08:00:00'
time2 = '2024-09-01 07:59:59'
begintime = str_data_to_num(time1)
endtime = str_data_to_num(time2)
ss = get_grafana_login()
print('登录成功')
for pf_num in [1]: # 1,3,2,4
respon1 = get_respon1(ss, begintime, endtime, pf_num)
if respon1 is not None:
print(respon1.time.max())
print(pf_num, time1, time2, respon1.shape[0])
else:
print(pf_num, '取数失败,无法获取相关信息。')
return respon1