[Twisted-Python] Looping
Phil Mayers
p.mayers at imperial.ac.uk
Sat Sep 20 04:37:46 MDT 2008
David Wilson wrote:
> Hi All,
> I'm trying to pick up Twisted and I'm having trouble with looping.
>
> I expected that a Deferred returned from a looping call would be
> available after each call. But it's only available after the loop is
It's not, and if you think about it, it can't - a loopingcall is setup
once and run indefinitely, who would you be "returning" the deferreds
to, and how?
Just call your handler from within your loopingcall i.e.
def check_file(fp, cb):
# blah blah
for line in lines:
cb(line)
> stopped. Am I looking for a different class?
>
> Thanks,
> Dave
>
> p.s. Ultimately I'd like to watch a file and post any new lines up to
> an HTTP server. If there is a direct way to get there, please let me
> know. Thanks!
The code you show isn't a very robust way of following a file. My advice
would be to run "tail -F -q name" in a sub-process and accumulate the
output.
You need to be aware when watching an external file that when you read,
the whole line might not have been written, so you need to do something
like this:
buffer = ''
def check(file, handler):
buffer += file.read()
if not '\n' in buffer:
return
lines = buffer.split('\n')
# the final "line" in the buffer doesn't have a terminating
# \n, make it be the buffer and drop it from out list
buffer = lines.pop()
for line in lines:
handler(line)
More information about the Twisted-Python
mailing list