Don't know how to develop While True, Try loop

Viewed 26

I am beginner and writing code to read value in every specific time and save it into different file and folder. Used time sleep, while True, try loop. How to do below action? 1st I would like to shift another action if connection fails or can't read value/lost connection (tried to write 0 value if connection fail). 2nd is when I using time sleep, some times it miss sequence (I wanted to write 00:01, 0:02, 0:03 but sometimes it prints 00:01, 00:03, missing 00:02). Thank you.

while True:
    try:
        tStart = time.time()
        t_round_to_min = round(tStart/60)*60
        t_write_time = datetime.fromtimestamp(t_round_to_min).strftime('%Y/%m/%d %H:%M')
        while len(list0)<60:
            value1 = read("x1") # connects to server and get value
            list0.append(value1)
            d[value1]=list0
            a = 1
            b = 1
            time.sleep(0.5)
        if len(list0) == 60:
            avg0 = (sum(list0))/(len(list0))
            avg9 = a/b
            list9.append(avg9)
            d[avg9]=list9
            list0.clear()
        with open(filename, "a", newline='') as f_output:
            csv_output = csv.writer(f_output, delimiter=";")
            csv_output.writerow(['Name', t_write_time, "%.3f" % avg0,])
        if len(list9) == 10:
            list9.clear()
            break
    # except Exception:
        # print("Bug")
        # break
    except:
        value1 = 0
0 Answers
Related