'''pipe module by June, who got inspiration from Steven D. Majewski's post
at http://groups.google.com/groups?selm=mailman.996817505.6289.python-list%40python.org
Usage e.g.:
>>> from pipe import *
>>> notDivBy3 = Test(lambda x: x % 3 )
>>> NotDivBy3Odd = odd|notDivBy3
>>> firstTen= Count(10)
>>> r=GenPipe(Ints())|firstTen|oddNotDivBy3
>>> for each in r:
.... print each
1
5
7
>>> isPyFile=Test(lambda s:s.split('.')[-1].lower() in ('py','pyw'))
>>> firstTenPythonFilesfromTheParentRecursively=GenPipe(Files('..'))|isPyFile|Count(10)
>>> for each in firstTenPythonFilesfromTheParentRecursively:
.... print each
'''
from __future__ import generators
class GenPipe:
def __init__(self, generator):
self.gen = generator #sanity check omitted
def __or__(self,nextPipe):
self.gen=nextPipe._run(self.gen)
return self
def __iter__(self):
return self.gen
class PipeFilter:
def __init__(self):
self._followingPipes=[]
def __or__(self,nextPipe):
self._followingPipes+=(nextPipe,)
return self
def _run(self,gen):
gen=self.run(gen)
while self._followingPipes:
gen=self._followingPipes[0].run(gen)
self._followingPipes.pop(0)
return gen
def run(self,gen):
raise NotImplementedError
class Test(PipeFilter):
def __init__(self,test):
PipeFilter.__init__(self)
self.test=test
def run(self,gen):
for x in gen:
if self.test(x):
yield x
class Quit(PipeFilter):
def __init__(self,test):
PipeFilter.__init__(self)
self.test=test
def run(self,gen):
for x in gen:
if self.test(x):
raise StopIteration
else:
yield x
class Count(PipeFilter):
def __init__(self,n):
PipeFilter.__init__(self)
self.n=n
def run(self,gen):
for x in gen:
yield x
self.n -= 1
if self.n == 0 :
break
def Ints():
n = 0
while 1:
yield n
n += 1
def Files( start ):
import os
for file in os.listdir( start ):
file = os.path.join( start, file )
if os.path.isfile( file ): yield file
elif os.path.isdir(file):
for more in Files( file ):
yield more
odd = Test(lambda x:x % 2)