1 #!/usr/bin/env python 2 3 """ 4 Example of concurrency when reading files. 5 6 See: http://wiki.python.org/moin/Concurrency/99Bottles 7 8 Based on the generator version. 9 """ 10 11 import pprocess 12 import time 13 import re 14 15 def follow(ch, fname): 16 f = file(fname) 17 f.seek(0,2) # go to the end 18 while True: 19 l = f.readline() 20 if not l: # no data 21 time.sleep(.1) 22 else: 23 ch.send(l) 24 25 def grep(ch, lines, pattern): 26 regex = re.compile(pattern) 27 for l in lines: 28 if regex.match(l): 29 ch.send(l) 30 31 def printer(lines): 32 for l in lines: 33 print l.strip() 34 35 def multigrep(ch, pattern): 36 queue = pprocess.Queue(continuous=1) 37 multifollow = queue.manage(follow) 38 multifollow('test') # '/var/log/system.log' 39 multifollow('test2') 40 multifollow('test3') 41 42 # Handle incoming lines using the specified pattern. 43 grep(ch, queue, pattern) 44 45 # Permit multiple simultaneous grep activities. 46 queue = pprocess.Queue(continuous=1) 47 multigrep = queue.manage(multigrep) 48 multigrep(".*pants.*") 49 multigrep(".*trousers.*") 50 multigrep(".*shorts.*") 51 52 p = printer(queue) 53 54 # vim: tabstop=4 expandtab shiftwidth=4