python - 指定时间内保存9600端口数据

标签 python python-3.x save port listen

我正在使用 Arduino 并从我的护罩和传感器获取值。由于监听端口 9600,我还将其中一些发送到serial.println。我正在监听端口 9600 并将这些值保存到 txt。之后,我将这些值上传到数据库并使用 Web 服务。

但是我无法在给定时间内保存 9600 端口。因为如果我没有关闭 python 应用程序,它就永远不会关闭,也永远不会保存 txt 文件。

我的代码如下。我想每 1 分钟保存一次 txt。

我该怎么做?

import serial
ser = serial.Serial('/dev/tty.usbmodem1411', 9600, timeout=1)
while 1:
    line = ser.readline()   # read a '\n' terminated line
    line2=line.decode("utf-8")
    ths = open("/Users/macproretina//Desktop/data.txt", "a")
    ths.write(line2)
ser.close()

最佳答案

您可以使用一个简单的计时器来停止循环。我清理了一些资源管理,上下文管理器非常有用。

import threading
from contextlib import closing
import serial

continue_looping = True
def stopper():
    global continue_looping
    continue_looping = False

timer = threading.Timer(60, stopper)
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()

由于串行超时,它可能会有点关闭。请注意,如果您在需要时调用 f.flush(),您就会将输出写入文件。

关于python - 指定时间内保存9600端口数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16595830/

相关文章:

python - 'str' 对象没有属性 'decode'

python连接到docker外的postgres docker实例

cakephp - 尝试在CakePHP 2.0中保存HABTM模型数据

python - 获取与值匹配的数组元素的索引

python - 使用 swift 从网络服务器上的 python 脚本获取数据

python - Pandas.DataFrame 按索引间隔选择

python - 如何循环数据框中的列表?

java - 在android studio的本地存储中保存小串数据

windows - 将图像名称及其大小保存到 Windows 中的文件中

python - 用 Python 抓取 NSE 期权链数据