【问题标题】:How to read streaming data from .temp file and feed it to the function? [duplicate]如何从 .t​​emp 文件中读取流数据并将其提供给函数? [复制]
【发布时间】:2019-10-28 01:01:03
【问题描述】:

我有来自许多传感器的流数据,这些数据每秒都会更新到计算机上的 .temp 文件中。我正在尝试找到在数据到达时顺序读取这些数据并将其提供给我的函数的方法,该函数应该对此流数据执行计算。

有没有办法从 .tmp 文件中读取此类数据,并在数据到达时在同一个实例中执行计算?

【问题讨论】:

  • 请给我们示例数据以及您的预期输出

标签: python temporary-files


【解决方案1】:

也许这样的事情会帮助我创建两个 python 文件,一个读取器和一个写入器:

例如,我的作者将每秒将带有键 age 的 json 字符串添加到文本文件中:

import random
import time
with open("test.txt", "a") as t:
    while True:
        time.sleep(1)
        t.write('{"age": ' + str(random.randint(1, 100)) + '}\n')
        t.flush()

阅读器现在将读取最新写入的更改行并计算此数据的median

import json
import statistics

agearray = []

with open("test.txt", "rb") as t:
    current_filesize = t.seek(0, 2)
    while True:
        new_filesize = t.seek(0, 2)
        if new_filesize > current_filesize:
            print("file changed")
            print(new_filesize, current_filesize)
            t.seek(current_filesize)
            readsize = new_filesize - current_filesize
            data = t.read(readsize)
            myjson = json.loads(data.decode("utf-8"))
            print(myjson)
            agearray.append(myjson["age"])
            print(statistics.median(agearray))
            current_filesize = new_filesize

Jep 这不是最好的例子,但这将是我的方法。
您必须在两个不同的线程中启动文件,例如 2x cmd 或 git bash... p>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-22
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    • 2019-09-15
    • 2020-12-29
    相关资源
    最近更新 更多