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

One thought on “Python Function Grep In Python

  1. 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 to t0mmyw Cancel reply