"Grep" in Python


I use Python as a command line tool. I wanted to be able to do something similar to dir() | grep cmd to find out what packages had been loaded and variables created. I got sick of searching the net and finding nothing, so here's a simple script that does effectively the same thing (with slightly more tedious syntax):
#py grep command #sample command: grep("^x",dir()) #syntax: grep(regexp_string,list_of_strings_to_search) import re def grep(string,list): expr = re.compile(string) for text in list: match = expr.search(text) if match != None: print match.string # Two alternate solutions, courtesy of Gene H # These are more elegant, and more detailed descriptions can be found here: # http://www.faqs.org/docs/diveintopython/apihelper_filter.html # http://www.faqs.org/docs/diveintopython/regression_filter.html def grep(string,list): expr = re.compile(string) return [elem for elem in list if expr.match(elem)] def grep(string,list): expr = re.compile(string) return filter(expr.search,list) # Note a subtle difference between the above two: # because the first uses expr.match(), it will only return exact matches # while the latter will return a list containing strings that contain the # search string in any position # e.g.: # list = ['normalize','size','nonzero','zenith'] # grep('ze',list) # First one returns: ['zenith'] # Second one returns: ['normalize','size','nonzero','zenith']

If you know of a better (i.e. cleverer) way to accomplish this same feat, please let me know!
Two of the solutions above were provided by a visitor, and I think they are a better solution to the problem presented here.
Personally, I haven't ended up using the 'grep' function as much as I expected; instead I tend to get by on using the Python debugger (pdb) and working on a smaller globals()/locals() list and using who/whos at the ipython command line.

If you are interested in using python on the unix command line in place of grep, I recommend the second hit on google


Home ]Astronomy ]Teaching ]Outreach ]Software ]Contact Me ]About Me ]CV ]Site Map ]