Python 以每分钟 600x-1200x 的速度读取 txt 文件的后果

Python consequences of reading txt file 600x-1200x per minute

以每分钟 python 高达 1200 次的速度读取 txt 文件是否有任何后果?

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

(我正在使用 Raspberry pi)

代码性质:

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)

如果文件由子进程附加,则更容易,只需将标准输出通过管道传输到您的函数即可。