From pythondev-dang at lazytwinacres.net Tue Mar 16 09:15:01 2004 From: pythondev-dang at lazytwinacres.net (pythondev-dang) Date: Tue, 16 Mar 2004 19:15:01 +0500 Subject: [IPython-dev] IPython interface to system grep w/results in a Python list Message-ID: <20040316141501.21064.qmail@server265.com> """This function implements a simple shell out to grep. You can enable it by copying it to your ~/.ipython directory and putting execfile = magic_grep.py in your ipythonrc file. Code contributed by Daniel 'Dang' Griffith , inspired by magic_grepl.py by Gever Tulley, available at . """ import os def magic_grep(self, parameter_s=''): """Search for a pattern in a list of files. It shells out to the operating system. Usage: @grep pattern [files] - pattern: any regular expression pattern which the grep on your system will accept. - files: list of files to scan. It can contain standard operating system wildcards. """ # if used as a function within the shell, the parameters are shifted. if (parameter_s == '' and type(self) == type('')): parameter_s = self p = os.popen3('grep %s' % parameter_s) errval = p[2].readlines() if errval: print ''.join(errval) return None retval = [i[:-1] for i in p[1].readlines()] # remove trailing newline return retval # Add the new magic function to the class dict: from IPython.iplib import InteractiveShell InteractiveShell.magic_grep = magic_grep # Uncomment the 'del' statement to remove the global name to keep global namespace clean. # Don't worry, the copy bound to IPython stays, we're just removing the global name. # You won't be able to use this as a function as easily, but grep will work as though # it were part of the shell. If necessary, you could still do: # result = InteractiveShell.magic_grep(InteractiveShell(''), grep_parameters_in_a_string) # If you keep magic_grep in the global namespace, you can simply do this: # result = magic_grep(grep_parameters_in_a_string) # parameters_in_a_string excludes the command 'grep' itself. E.g.: # result = magic_grep('-l HELP *.*') # binds result to the results of the grep command. #del magic_grep