#!/usr/bin/python3.1 ''' Prints (extract) a function fron a python file, shifting the indentation as far left as possible. If more than one function with the same name exists in the file, only the first function will be printed. This software is provided as is with no warranties. Use at your own risk. Redistribution and use with or without modification, are permitted. This applies worldwide. Yves Dorfsman, April 2010 ''' class parserdata(object): import re indent = 0 flag = True pattern = str() compiled_pattern = object() parser = object() findpattern = re.compile('^\s*def\s*') x = parserdata() def parser1(line): import re matches = x.compiled_pattern.match(line) if matches: x.indent = line.find('def') # Got the line, we switch parser, and... x.parser = parser2 # ... parse this very line too before reading the next. x.parser(line) def parser2(line): if len(line) > x.indent: lhs = line[0:x.indent-1] rhs = line[x.indent:] if not lhs.isspace(): x.flag = False return print(rhs, end='') else: print(line, end='') import sys import re if len(sys.argv) != 3: print('\nSyntax error.\n', file=sys.stderr) print('Needs two arguments:', file=sys.stderr) print(' -the name of the python file', file=sys.stderr) print(' -the name of the function to extract\n', file=sys.stderr) sys.exit(1) file = sys.argv[1] x.pattern = '^\s*def\s*' + sys.argv[2] + '\s*\(' x.compiled_pattern = re.compile(x.pattern) x.parser = parser1 f = open(file) for line in f: if x.flag: x.parser(line) else: # indentation has moved back break f.close()