search

Home  >  Q&A  >  body text

linux - python如何从后往前读取文件?

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

PHPzPHPz2807 days ago924

reply all(3)I'll reply

  • PHPz

    PHPz2017-04-18 09:27:24

    file.readlines()[-50:]

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-18 09:27:24

    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

    reply
    0
  • 怪我咯

    怪我咯2017-04-18 09:27:24

    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 

    reply
    0
  • Cancelreply