Python Function Grep In Python

I am replacing this post (which was just normal grep in Python) with a script that will look for a search term and print out the last py method (def) it was seen in.

#!/usr/bin/python

import re
import sys

linenumb = 1
srchterm = ""
srchfunc = ""

lastfnum = 0
lastfunc = ""

if (len(sys.argv) < 2):
	print("Usage: %s <regex search term> [<function name>]" % (sys.argv[0]))
	sys.exit(0)

if (len(sys.argv) >= 2):
	srchterm = sys.argv[1]

if (len(sys.argv) >= 3):
	srchfunc = sys.argv[2]

while (1):
	lineread = sys.stdin.readline()
	
	if (not lineread):
		break
	
	lineread = lineread.rstrip()
	
	if (re.match("^def .*$", lineread)):
		lastfnum = linenumb
		lastfunc = lineread
	
	if (re.match("^[\t ]+.*" + srchterm + ".*$", lineread)):
		if ((lastfunc == "") or (re.match("^def " + srchfunc + ".*$", lastfunc))):
			if (lastfunc != ""):
				print("[*] [%d] %s" % (lastfnum, lastfunc))
				
				lastfnum = 0
				lastfunc = ""
			
			print("[-] [%d] %s" % (linenumb, lineread))
	
	linenumb += 1

Advertisements
Python Function Grep In Python

One thought on “Python Function Grep In Python

  1. t0mmyw says:

    why not use grep with -B and -A?

    shows lines before and after the line that had the matching text.

    -A NUM, –after-context=NUM
    Print NUM lines of trailing context after matching lines.
    Places a line containing — between contiguous groups of
    matches.

    -B NUM, –before-context=NUM
    Print NUM lines of leading context before matching lines.
    Places a line containing — between contiguous groups of
    matches.

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