Notes & Code Snippets

Read notes about design & development, or useful scripts and bits of code from me

Parse an HTML page for Python code

April 01, 2011

Keywords: python php html

This script is intended to simulate the way PHP works when embedded in an HTML page. It will take an HTML page and find code blocks of Python, and execute them.

#! /usr/local/bin/python
def preprocess(__preprocess__file__):
    try:
        __preprocess__f__ = open(__preprocess__file__, 'r')
        __preprocess__execScript__ = ""
        __preprocess__execMode__ = False
        while True:
            __preprocess__x__ = __preprocess__f__.readline()
            if not __preprocess__x__:
                break
            if __preprocess__x__ == '<?\n':
                __preprocess__execMode__ = True
                __preprocess__x__ = ""
            if __preprocess__execMode__:
                if __preprocess__x__ == '?>\n':
                    exec(__preprocess__execScript__)
                    __preprocess__execScript__ = ""
                    __preprocess__execMode__ = False
                    __preprocess__x__ = ""
                else:
                    __preprocess__execScript__ += __preprocess__x__
            else:
                __preprocess__x__ = __preprocess__x__.replace('\n', '')
                if __preprocess__x__.find('<?=') is not -1:
                    __preprocess__y__ = ""
                    __preprocess__x__ = __preprocess__x__.split('<?=')
                    for __preprocess__z__ in __preprocess__x__:
                        __preprocess__found__ = __preprocess__z__.find('?>')
                        if __preprocess__found__ is not -1:
                            __preprocess__operation__ = __preprocess__z__[0:__preprocess__found__]
                            __preprocess__y__ += str(eval(__preprocess__operation__))
                            __preprocess__y__ += __preprocess__z__[__preprocess__found__ + 2:]
                        else:
                            __preprocess__y__ += __preprocess__z__
                    __preprocess__x__ = __preprocess__y__
                    del __preprocess__y__
                    del __preprocess__z__
                print __preprocess__x__
        __preprocess__f__.close()
    except Exception, e:
        print e

Back to top