开发者

How can I block on readline() in python so I don't have to poll? [duplicate]

开发者 https://www.devze.com 2023-02-04 23:26 出处:网络
This question already has ans开发者_如何转开发wers here: Closed 12 years ago. Possible Duplicate:
This question already has ans开发者_如何转开发wers here: Closed 12 years ago.

Possible Duplicate:

tail -f in python with no time.sleep

I am trying to monitor a log file that is being written to (like tail -f), and I can't figure out how to make readline() block once it reaches eof. All of my googling has only turned up solutions to make things NON-blocking. Does anyone know a way to make a call like this block, so I DON'T have to poll? (I'm perfectly capable of polling and sleeping already, so if you suggest that I'm going to rate you down.)

fh = open('logfile')
# I only want new output, so seek to the end of the file
fh.seek(-1,2)
while True:
   # I want this to block until the file has new output, 
   # but it sees eof and returns '' immediately
   line = fh.readline()
   # ... process the line


You can't really 'block without polling'. You have to check if the file has new data for you at some point. When you write constantly updating processes, you have to poll eventually, unless you're writing ISRs (interrupt service routines) in assembly. Even then, the CPU is constantly polling for any pending interrupts.

Here's your code that checks the file for new data every second. This keeps the CPU usage minimal.

fh = open('logfile')
# I only want new output, so seek to the end of the file
fh.seek(-1,2)
# 'while True' is sort of bad style unless you have a VERY good reason.
# Use a variable. This way you can exit nicely from the loop
done = False 
while not done:
   # I want this to block until the file has new output, 
   # but it sees eof and returns '' immediately
   line = fh.readline()
   if not line:
       time.sleep(1)
       continue
   # ... process the line
       #... if ready to exit:
           done = True
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号