使用 python 读取 txt 文件高达每分钟 1200 次,会产生任何后果吗?
我正在做一个项目,其中一个程序处于永恒循环中,并且向其传递任何参数并不容易(不想使用线程或多处理(在解释器之间传递变量)来传递参数)。
(我使用的是树莓派)
代码的性质:
import time
while True:
with open('args.txt', 'r') as FILE:
ARGS = FILE.read()
time.sleep(0.05)
如果这不安全,是否有更好的解决方案如何保持程序运行,同时每 0.05 秒检查一次以读取某些外部数据源? 提前致谢
最佳答案
如果您是 Linux 用户,您可能会熟悉 tail -f filename.txt
。
Instead of just displaying the last few lines and exiting, tail displays the lines and then monitors the file. As new lines are added to the file by another process, tail updates the display.
If your usecase is to read newlines appended to a file here's an implementation of tail -f
.
file = open(filename,'r')
#Find the size of the file and move to the end
st_results = os.stat(filename)
st_size = st_results[6]
file.seek(st_size)
import time
while 1:
where = file.tell()
line = file.readline()
if not line:
time.sleep(0.05)
file.seek(where)
else:
print line, # already has newline
每 0.05 秒持续检查一次并打印附加的新行。
或者这里是 tail -f
作为子进程:
from subprocess import Popen, PIPE, STDOUT
p = Popen(["tail", "-f", "/the/file"], stdin=PIPE, stdout=PIPE, stderr=STDOUT)
for line in p.stdout:
print(line)
如果文件由子进程附加,则更容易,只需将标准输出通过管道传输到您的函数即可。
关于Python每分钟读取txt文件600x-1200x的后果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52568711/