Writing Grep In Python

Files can be fun to work with.  This version uses coroutines and is based off an examples provide by David Beazley, head over to dabeaz.com if want your mind blown.  I also wrote this over at Codepad if you want to run it yourself, http://codepad.org/SnDqZCcx

Python 3's Source Code:
def coroutine(func):
#- Decorator function to supports coroutines.
#- Coroutines functions are a little strange in python and require to have next or send called on them.
#- This function is the example provided by David Beazley
    def start(*args,**kwargs):
        cr = func(*args,**kwargs)
        cr.next() # You can also use send to advance a coroutine
        return(cr)
    return(start)

@coroutine
def grep(pattern):
    #- This is where the magic happens.
    try:
        while True:
            line = (yield) # This is where the pattern string is passed in.
            if pattern in line: # Checking if pattern is in the current line
                print(line) # Prints the whole line if found

    except GeneratorExit:
        print("Closing the coroutine.")

if __name__ == '__main__':
    g = grep("Bueller") # This is where you pass in the pattern

    # - Sending in non-Bueller strings
    g.send("Whats the score?\n") # Dev Note: \n = new line
    g.send("Nothing and Nothing.\n")
    g.send("Who's winning?\n")
    g.send("The Bears.\n")

    #- Sending in a Bueller string
    g.send("Random quotes from Ferris Bueller's Day Off are fun!\n")
    g.close() # Closes the coroutine and causes the code stored in the GeneratorExit exception to execute

Standard Out:

Random quotes from Ferris Bueller's Day Off are fun!

Closing the coroutine.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s