#!/usr/bin/python # Encoding: iso8859-1 import getopt, os, os.path, re, sys import html def fix(lines): # Fix script indentation indent = None for i in range(0, len(lines)): if indent is None: line = lines[i].rstrip().expandtabs() if i and line: indent = 0 while line[indent].isspace(): indent += 1 line = line[indent:] lines[i] = line else: lines[i] = lines[i].rstrip().expandtabs()[indent:] return lines def process(infp, outfp, infilename = None, outfilename = None): _globals = {} _locals = None _globals['doc'] = infilename _globals.update(vars(html)) try: import local except ImportError: pass else: _globals.update(vars(local)) start_re = re.compile(r'<\?python\s') end_re = re.compile(r'\?>') lineno = 0 in_script = 0 script = None for line in infp: lineno += 1 pos = 0 while 1: if script is None: mo = start_re.search(line, pos) if mo: outfp.write(line[pos:mo.start()]) script = [] pos = mo.end() else: outfp.write(line[pos:]) break else: mo = end_re.search(line, pos) if mo: script.append(line[pos:mo.start()]) script = '\n'.join(fix(script)) + '\n' # Execute the script redirecting the stdout stdout = sys.stdout sys.stdout = outfp sys.path.insert(0, os.path.dirname(infilename)) exec(script, _globals, _locals) del sys.path[0] sys.stdout = stdout script = None pos = mo.end() else: script.append(line[pos:]) break def usage(): sys.stderr.write('pyhtml.py [-e|--encoding ] [-o|--output ] [ ...]\n') def main(): try: opts, args = getopt.getopt(sys.argv[1:], 'he:o:', ['help', 'encoding=', 'output=']) except getopt.GetoptError: usage() sys.exit(2) outfilename = None outfp = sys.stdout encoding = 'iso8859-1' for opt, arg in opts: if opt in ('-h', '--help'): usage() sys.exit() elif opt in ('-e', '--encoding'): html.encoding = arg elif opt in ('-o', '--output'): outfilename = arg outfp = file(arg, 'wt') try: if args: for arg in args: infilename = arg infp = file(arg, 'rt') process(infp, outfp, infilename, outfilename) else: infp = sys.stdin infilename = None process(infp, outfp, infilename, outfilename) except: if outfilename: os.remove(outfilename) raise if __name__ == '__main__': main()