tail -f in python with no time.sleep

后端 未结 10 1892
耶瑟儿~
耶瑟儿~ 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条回答
  •  情书的邮戳
    2020-11-30 03:09

    Most implementations I've seen use readlines() / sleep(). A solution based on inotify or similar might be faster but consider this:

    • once libinotify tells you a file has changed you would end up using readlines() anyway

    • calling readlines() against a file which hasn't changed, which is what you would end up doing without libinotify, is already a pretty fast operation:

      giampaolo@ubuntu:~$ python -m timeit -s "f = open('foo.py', 'r'); f.read()" -c "f.readlines()" 1000000 loops, best of 3: 0.41 usec per loop

    Having said this, considering that any solution similar to libinotify has portability issues, I might reconsider using readlines() / sleep(). See: http://code.activestate.com/recipes/577968-log-watcher-tail-f-log/

提交回复
热议问题