[IPython-dev] IPython interface to system grep w/results in a Python list

pythondev-dang pythondev-dang at lazytwinacres.net
Tue Mar 16 09:15:01 EST 2004


"""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 <pythondev-dang at lazytwinacres.net>,
inspired by magic_grepl.py by Gever Tulley, available at
<http://www.scipy.net/pipermail/scipy-cvs/2003-September/001937.html>.
"""

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




More information about the IPython-dev mailing list