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

标签 python file text hardware corruption

使用 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/

相关文章:

python - 导入keras时出错 ModuleNotFoundError : No module named 'tensorflow.examples' ; 'tensorflow' is not a package

python - Keras自定义丢失错误: Unknown loss function

javascript - 在 onmousedown 的 Raphael 函数中包含 labelPath

html - 仅在不影响背景的情况下在文本上方留出空白的 CSS 代码?

python - utf-8 pytest 输出用\x 转换为 ascii

file - 此时在基本的 if then 语句中出乎意料

python - 检查文件中是否有与输入匹配的文本

Ruby 在复制文件时显示进度

javascript - 隐藏元素的部分内容

Python,从方法返回/处理复杂数据的最佳方式