1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/examples/concurrency-sig/bottles.py Thu Jun 04 22:28:43 2009 +0200
1.3 @@ -0,0 +1,54 @@
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):
1.35 + for l in lines:
1.36 + print l.strip()
1.37 +
1.38 +def multigrep(ch, pattern):
1.39 + queue = pprocess.Queue(continuous=1)
1.40 + multifollow = queue.manage(follow)
1.41 + multifollow('test') # '/var/log/system.log'
1.42 + multifollow('test2')
1.43 + multifollow('test3')
1.44 +
1.45 + # Handle incoming lines using the specified pattern.
1.46 + grep(ch, queue, pattern)
1.47 +
1.48 +# Permit multiple simultaneous grep activities.
1.49 +queue = pprocess.Queue(continuous=1)
1.50 +multigrep = queue.manage(multigrep)
1.51 +multigrep(".*pants.*")
1.52 +multigrep(".*trousers.*")
1.53 +multigrep(".*shorts.*")
1.54 +
1.55 +p = printer(queue)
1.56 +
1.57 +# vim: tabstop=4 expandtab shiftwidth=4