如何在Python中使用循环计时器

2024-06-09 16:34:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我想监听串行端口,每15秒保存一次。 但我不能在循环中使用时间。

错误如下。

File "serial-reader.py", line 13 timer.start() ^ IndentationError: expected an indented block

我怎样才能解决这个问题?

    import threading
from contextlib import closing
import serial
counter = 0
continue_looping = True
def stopper():
    global continue_looping
    continue_looping = False

timer = threading.Timer(15, stopper)

while (counter < 9 ):
timer.start()
with open("/Users/macproretina/Desktop/data.txt", 'w') as out_file:
    with closing(serial.Serial('/dev/tty.usbmodem1411', 9600, timeout=1)) as ser:
        while continue_looping:
            line = ser.readline()   # read a '\n' terminated line
            out_file.write(line.decode('utf-8'))
            out_file.flush()
            counter = counter +1

Tags: importwithlinecounterserialoutstartfile