Start New Discussion within our Software Development Community

This is a command line utility which lists the names of all functions defined in a python source file with a def <name> statement

#!/usr/bin/env python

# printdef.py
# prints the names of all function definitions found in a program
# usage: python printdef.py myprogram.py

from tokenize import generate_tokens, NAME

def getDefSequence(programPath):
  # generator of the names of all python fonctions defined in file programPath
  tokens = generate_tokens(open(programPath, "r").readline)
  for token in tokens:
    if token[0] == NAME and token[1] == "def":
      func = tokens.next()
      if func[0] == NAME:
        yield func[1]


if __name__ == "__main__":
  import sys
  programPath = sys.argv[-1]
  if programPath[-3:] != ".py":
    print "usage: printdefs.py <path to '.py' file>"
    sys.exit(-1)
  for name in getDefSequence(programPath):
    print name
The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.