[英]How to transfer live data from one Python script to another?
Currently I am writing on a program with 2 separate file Main.py and App.py, Main.py takes in readings such as distance and temperature and writes it in a file named data.txt and App.py then reads from the text file.目前我正在编写一个带有 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
The problem now is that the text file gets flooded with readings and over time will slow down the program and I do know it is not the most efficient way to go about doing this but I am just getting into python, so is there anyway to transfer the data directly from Main.py to App.py or a way to delete the text file reading after reaching a certain number of lines?现在的问题是文本文件被读数淹没,随着时间的推移会减慢程序的速度,我知道这不是最有效的方法,但我刚开始使用 python,所以无论如何要传输数据直接从Main.py到App.py还是达到一定行数后删除文本文件读取的方法? Example after 50 lines it starts deleting/overwriting the lines?
例如在 50 行之后它开始删除/覆盖这些行?
You can use the pythons multiprocessing module and then implement a pipe between two modules.您可以使用 python 多处理模块,然后在两个模块之间实现管道。 You may also use a queue but pipe improves the performance of your programme as Queue is built on top of Pipe.
您也可以使用队列,但管道提高了程序的性能,因为队列建立在管道之上。 But pipe has its disadvantages too:
但是管道也有它的缺点:
Refer these links to better understand the topic:请参阅这些链接以更好地理解该主题:
Regarding how to delete a block of code or script automatically please refer this stack overflow question:关于如何自动删除代码块或脚本块,请参考这个堆栈溢出问题:
How to make scripts auto-delete at the end of execution? 如何使脚本在执行结束时自动删除?
Since you need to update the file without automatically deleting it here are some answers which might help:由于您需要在不自动删除的情况下更新文件,这里有一些可能有帮助的答案:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.