UnboundLocalError:分配前已引用局部变量“ data_average_ug”

时间:2018-12-11 17:45:18

标签: python-3.x

我遇到此错误:

STF started at  Tue Dec 11 12:22:25 2018 0
Traceback (most recent call last):
  File "C:\Users\user\Desktop\environet\main.py", line 8, in <module>
    STF_pms()
  File "C:\Users\user\Desktop\environet\STFV062.py", line 59, in STF_pms
    average_ug = DT_data_average_ug(t1,t2,data_id_list[s][3],bg_offset)
  File "C:\Users\John.Z.Wen\Desktop\environet\dusttrak_average_ug.py", line 29,
in DT_data_average_ug
    return data_average_ug
UnboundLocalError: local variable 'data_average_ug' referenced before assignment

主要py文件如下:

import time
from STFV062 import STF_pms
from custommodule1 import function1
starttime=time.time()#program start time, to control loop
while True:
    function1()
    STF_pms()
    print('sleep 5 min')
    time.sleep(300 - ((time.time() - starttime) % 300))

问题出在文件STF_pms()中的STFV062.py

from dusttrak_average_ug import DT_data_average_ug
def STF_pms():
    #get t1 t2 id offset
    data_average_ug = DT_data_average_ug(t1,t2,id,offset)
    if data_average > xxx:
       yyy
    else:
    print('good')

dusttrak_average_ug.py如下:

import requests
import re
import time
#input t1 t2(ms), data id, offset
def DT_data_average_ug(t1epoch_milisecond,t2epoch_milisecond,data_id,offset):
#data_id_list[s][2] is data id
    headers = {
    'Accept': 'application/json',
    'Authorization': 'Bearer token',
    'Content-Type': 'application/json',
    }
    data = '{"data_point_id":"%s", "from":"%d","to":"%d"}'%(data_id,t1epoch_milisecond,t2epoch_milisecond)
    response = requests.post('https://api.application.com/search/data_points', headers=headers, data=data)
    i_measurements = response.text.find('measurements')
    i_frist_data = i_measurements + 16 #offset to first data point
    data_rawlist = re.findall(r"\[\d{13},\d*.\d*\]",response.text[i_measurements:])
    data_list =[]
    i=0
    pm_sum=0
    print(len(data_rawlist))
    for i in range(len(data_rawlist)):
        col1 = data_rawlist[i][1:14]
        col2 = data_rawlist[i][16:-1]
        data_list.append([col1,col2])
        pm_sum = pm_sum + float(col2)
        data_average = pm_sum/len(data_rawlist) -offset#offset background.
        data_average_ug = data_average*1000
    #print "Station",data_id_list[s][0],"from",t1h,"to",t2h,"the hourly average",data_id_list[s][1],"is",data_average,"mg/m3"
    return data_average_ug

如果我使用以下方法在data_average_ug中呼叫test.py

from dusttrak_average_ug import DT_data_average_ug
cc = DT_data_average_ug(t1,t2,'id token',offset)
print (cc)

功能正常。有人可以教育我我做错了什么吗?

0 个答案:

没有答案