tail -f in python with no time.sleep

后端 未结 10 1861
耶瑟儿~
耶瑟儿~ 2020-11-30 02:45

I need to emulate \"tail -f\" in python, but I don\'t want to use time.sleep in the reading loop. I want something more elegant like some kind of blocking read, or select.se

10条回答
  •  Happy的楠姐
    2020-11-30 03:02

    To minimize the sleep issues I modified Tzury Bar Yochay's solution and now it polls quickly if there is activity and after a few seconds of no activity it only polls every second.

    import time
    
    def follow(thefile):
        thefile.seek(0,2)      # Go to the end of the file
        sleep = 0.00001
        while True:
            line = thefile.readline()
            if not line:
                time.sleep(sleep)    # Sleep briefly
                if sleep < 1.0:
                    sleep += 0.00001
                continue
            sleep = 0.00001
            yield line
    
    logfile = open("/var/log/system.log")
    loglines = follow(logfile)
    for line in loglines:
        print line,
    

提交回复
热议问题