linux - python如何从后往前读取文件?
PHPz
PHPz 2017-04-18 09:25:24
0
3
914

小弟想在web上显示log文件的最新的五十条,遇到这个问题,希望大家帮帮忙。不甚感激。

PHPz
PHPz

学习是最好的投资!

reply all(3)
PHPzhong

file.readlines()[-50:]

大家讲道理

Several ways:

  1. Use subprocess to adjust tail -f

  2. Use pyinotiy to monitor file changes

  3. Implement it by yourself, for example, first get the file size, read the last byte, then go back to the first n, which is the last line, and then go back in sequence

刘奇

Everything mentioned by the people above is feasible, but @nealnote's method will have performance problems if it reads large files. It is recommended to use @manong's subprocessunix系统自带的一个tailprogram to do it. The specific implementation is as follows:

import subprocess


fh = subprocess.Popen("tail -n 50 /var/log/dmesg", stdout=subprocess.PIPE, shell=True)
for line in fh.stdout.readlines():
    print(line.decode('ascii'), end="")

Run results:

...
...
rdac: device handler registered
device-mapper: multipath round-robin: version 1.0.0 loaded
EXT4-fs (sdd5): mounted filesystem with ordered data mode. Opts: 
EXT4-fs (sdd2): mounted filesystem with ordered data mode. Opts: 
EXT4-fs (dm-1): mounted filesystem with ordered data mode. Opts: 
EXT4-fs (dm-0): warning: maximal mount count reached, running e2fsck is recommended
EXT4-fs (dm-0): mounted filesystem with ordered data mode. Opts: 
Adding 1023996k swap on /dev/sdd3.  Priority:-1 extents:1 across:1023996k 
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template