python - 使用 readline() 轮询文件的更改适用于 macOS 但不适用于 Debian 9
问题描述
我想“轮询”文件以进行更改。
以下代码在带有 Python 3.8.6 的 macOS 10.15.7 上运行良好,但在带有 Python 3.7.3 的 Debian 9 上却不行。在 Debian 上,当我向要合并的文件添加新行时,它没有被识别并保持打印检查..
from time import sleep
from datetime import datetime
wait = 1
with open('file.log') as fp:
exit_pooling = False
while not exit_pooling:
print("*** check " + str(datetime.now()))
line = fp.readline()
if not line:
sleep(wait)
continue
else:
print('process line')
谢谢!
解决方案
使用 Python3.6 在 Ubuntu18.04 上按预期工作:
#!/usr/bin/env python3
from time import sleep
from datetime import datetime
from pathlib import Path
wait = 1
with Path('file.log').open() as fp:
exit_pooling = False
while not exit_pooling:
print("*** check " + str(datetime.now()))
line = fp.readline()
if not line:
sleep(wait)
else:
print(f'process line: {line}')
exit_pooling = line.strip() == 'exit'
推荐阅读
- apache-spark - 是否可以使用相同的代码读取 csv 或 parquet 文件
- apache-kafka - 对中间有队列的服务器的请求流是什么?
- javascript - 使用 XPath 将正则表达式单独的节点匹配到一个数组中
- javascript - 根据用户生成垫卡数量
- git - Git pull 通过“递归”策略创建合并
- angular - 如何将 Angular 2 与 Spring Boot 应用程序连接起来?
- javascript - 在 VueX 中存储 JSON 结构
- android - spannablestring 不加粗文本
- c - TCP头值初始化
- javascript - 异步功能不会第二次弹出