每分钟读取txt文件600x1200x的Python后果

2024-05-16 23:49:42 发布

您现在位置:Python中文网/ 问答频道 /正文

用python读取txt文件的次数高达每分钟1200次,会产生任何后果吗

我在做一个项目,其中一个程序是在永恒的循环,它不是很容易给它传递任何参数(不想使用线程或多处理(传递变量之间的解释程序)传递参数)

(我用的是覆盆子皮)

准则的性质:

import time
while True:
    with open('args.txt', 'r') as FILE:
        ARGS = FILE.read()
    time.sleep(0.05)

如果这是不安全的,有没有更好的解决方案,如何保持程序运行,同时检查每0.05秒读取一些外部数据源? 提前谢谢


Tags: 文件项目import程序txt参数覆盆子time
1条回答
网友
1楼 · 发布于 2024-05-16 23:49:42

如果您是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 ^{}.

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)

如果文件附加了一个子进程,那就更简单了,只需将stdout管道传输到函数中即可

相关问题 更多 >