[Tutor] invalid syntax? huh!?!
Scott Widney
SWidney@ci.las-vegas.nv.us
Fri, 18 Oct 2002 11:41:16 -0700
> Ok, I'm writing a script in Python 2.2 on windows that basically
> scans another python module and lists all the lines beginning
> with "class" and "def" in them. Basically, it will print out a
> reference to the module.
>
> Here is the script: (formatting a little mangled by outlook)
> --------------------------------------------------------
> #!/usr/bin/python
>
> "scans a python module and lists all classes and functions"
>
> import sys
> import re
>
> ModuleToScan = sys.argv[1]
>
> def SetRegExp():
> ScanClass = re.compile("class")
> ScanDef = re.compile("def")
>
> def ScanModule(ModuleToScan):
> fp = open(ModuleToScan)
> for line in fp.readlines()
> if ScanClass.search(line):
> print line
> else
> if ScanDef.search(line):
> print line
> fp.close()
> return
>
> SetRegExp()
> ScanModule(ModuleToScan)
> --------------------------------------------------------------
Did a little refactoring (just for fun), came up with this:
#####
#!/usr/bin/python
"""List all class and function declarations in a .py file"""
import re, sys
ScanClass = re.compile("class")
ScanDef = re.compile("def")
def ScanModule(ModuleToScan):
fp = open(ModuleToScan, 'r')
for line in fp.readlines():
if ScanClass.search(line):
print line
elif ScanDef.search(line):
print line
fp.close()
if __name__ == '__main__':
if len(sys.argv) < 2:
print "Usage: modscan <module filename> [...]"
sys.exit()
for fname in sys.argv[1:]:
print "Filename: %s" % (fname,)
ScanModule(fname)
#####
Seems to work, feel free to kick it around. Should run from the command line
with any number of filenames, and can be imported at the interactive prompt.
Scott