【问题标题】:How to transfer live data from one Python script to another?如何将实时数据从一个 Python 脚本传输到另一个?
【发布时间】:2021-03-01 08:45:42
【问题描述】:

目前我正在编写一个包含 2 个单独文件 Main.py 和 App.py 的程序,Main.py 读取距离和温度等读数,并将其写入名为 data.txt 和 App.py 的文件中,然后从文本文件。

#main.py

def scan():
  global object_temp, close_enough, real_distance #close enough writes true is someone is near

while True:
  f=open("data.txt","a+")
  a=str(scan())+"\n"
  f.write(a):
  log.log(a)
  f.close()



#data.txt 
#imagine this but with almost 60000 line each time I run it as it's printing every second
[26.03, 30.91, 126.5, False]
[25.97, 30.89, 125.69, False]
[25.97, 30.89, 124.74, False] 
.
.
etc



#app.py

def getValues():
    global prevValues
    f=open("data.txt","r")
    latestValue = str(f.read())
    f.close()
    #log.log(latestValue,"LATEST VALUES")
    latestValue = latestValue.split("\n")[-2].strip('][').split(', ')
    log.log(latestValue,"LATEST VALUES")
    if latestValue=="":
        return(prevValues)
    else:
        return(latestValue)
        prevValues=latestValue

现在的问题是文本文件被读数淹没,随着时间的推移会减慢程序的速度,我知道这不是最有效的方法,但我刚刚进入 python,所以有吗无论如何将数据直接从 Main.py 传输到 App.py 或在达到一定行数后删除文本文件读取的方法?例如 50 行后它开始删除/覆盖这些行?

【问题讨论】:

标签: python


【解决方案1】:

您可以使用 pythons 多处理模块,然后在两个模块之间实现管道。您也可以使用队列,但管道可以提高程序的性能,因为队列是建立在管道之上的。但是管道也有它的缺点:

  1. 一个 Pipe() 只能有两个端点。
  2. 一个 Queue() 可以有多个生产者和消费者。

参考这些链接以更好地理解主题:

  1. Passing data between separately running Python scripts
  2. Pipes vs Queues python documentation
  3. Pipes vs queues stack overflow answer

关于如何自动删除一段代码或脚本请参考这个堆栈溢出问题:

How to make scripts auto-delete at the end of execution?

由于您需要在不自动删除的情况下更新文件,这里有一些可能会有所帮助的答案:

  1. Is it possible for a running python program to overwrite itself?

【讨论】:

  • 是的,管道功能看起来和我需要的完全一样,感谢您的宝贵时间!
  • 关于脚本的删除,我不想完全删除脚本,但我想覆盖脚本中的行,保持行数不变,例如文本有 10 行时新行被添加到脚本中,脚本将删除/覆盖第 1 行,保持第 10 行。
猜你喜欢
  • 1970-01-01
  • 2014-07-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-12
相关资源
最近更新 更多