python 有没实时文件监控的 tail -F?

2016-09-03 00:56:14 +08:00
 masterzh01

tail -F 的源码是采用 inotify + select 方式来实现

python 的 pyinotify 库对 inotify 进行了封装,但貌似性能不是很好。

实现 tail-F: https://github.com/masterzh01/tail-F

5421 次点击
所在节点    Python
6 条回复
necomancer
2016-09-03 02:24:50 +08:00
from sys import argv
import collections


o = open(argv[1], 'r')
print(''.join(collections.deque(o, 5)).strip('\n')) # last 5 lines
o.seek(0,2) # jump to last line
while 1:
....line = o.readline()
....if line:
........print(line.strip('\n'))

就可以了吧……
masterzh01
2016-09-03 08:45:38 +08:00
@necomancer 不行, cpu , rotate.....( tail -F )
hasdream
2016-09-03 10:09:33 +08:00
```
import time

import time
def follow(thefile):
thefile.seek(0,2) # Go to the end of the file
while True:
line = thefile.readline()
if not line:
time.sleep(0.1) # Sleep briefly
continue
yield line

# Example use
if __name__ == '__main__':
logfile = open("access-log")
for line in follow(logfile):
print line,

```
necomancer
2016-09-03 13:20:33 +08:00
@masterzh01 CPU usage 问题加上 sleep 就行:

from sys import argv
import collections
import time

o = open(argv[1], 'r')
print(''.join(collections.deque(o, 5)).strip('\n')) # last 5 lines
o.seek(0,2) # jump to last line
while 1:
....line = o.readline()
....if not line:
........time.sleep(0.1)
........continue
....print(line.strip('\n'))
masterzh01
2016-09-03 22:32:17 +08:00
@hasdream @necomancer 事件驱动方式会更好些?
hasdream
2016-09-03 23:55:27 +08:00
@masterzh01 如果用事件来做基本没延迟 不过要复杂点还要对事件处理

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/303589

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX