1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/examples/concurrency-sig/bottles_heartbeat.py Fri Jun 05 01:46:07 2009 +0200
1.3 @@ -0,0 +1,59 @@
1.4 +#!/usr/bin/env python
1.5 +
1.6 +"""
1.7 +Example of concurrency when reading files.
1.8 +
1.9 +See: http://wiki.python.org/moin/Concurrency/99Bottles
1.10 +
1.11 +Based on the generator version.
1.12 +"""
1.13 +
1.14 +import pprocess
1.15 +import time
1.16 +import re
1.17 +
1.18 +def follow(ch, fname):
1.19 + f = file(fname)
1.20 + f.seek(0,2) # go to the end
1.21 + while True:
1.22 + l = f.readline()
1.23 + if not l: # no data
1.24 + time.sleep(.1)
1.25 + else:
1.26 + ch.send(l)
1.27 +
1.28 +def grep(ch, lines, pattern):
1.29 + regex = re.compile(pattern)
1.30 + for l in lines:
1.31 + if regex.match(l):
1.32 + ch.send(l)
1.33 +
1.34 +def printer(lines, delay=5000):
1.35 + while 1:
1.36 + lines.store(delay)
1.37 + if len(lines) > 0:
1.38 + l = lines.next()
1.39 + print l.strip()
1.40 + else:
1.41 + print "No input received for %d ms." % delay
1.42 +
1.43 +def multigrep(ch, pattern):
1.44 + queue = pprocess.Queue(continuous=1)
1.45 + multifollow = queue.manage(follow)
1.46 + multifollow('test') # '/var/log/system.log'
1.47 + multifollow('test2')
1.48 + multifollow('test3')
1.49 +
1.50 + # Handle incoming lines using the specified pattern.
1.51 + grep(ch, queue, pattern)
1.52 +
1.53 +# Permit multiple simultaneous grep activities.
1.54 +queue = pprocess.Queue(continuous=1)
1.55 +multigrep = queue.manage(multigrep)
1.56 +multigrep(".*pants.*")
1.57 +multigrep(".*trousers.*")
1.58 +multigrep(".*shorts.*")
1.59 +
1.60 +p = printer(queue)
1.61 +
1.62 +# vim: tabstop=4 expandtab shiftwidth=4