Parsing text file with #include and #define directives

python at python at
Fri Apr 25 13:56:10 CEST 2008


Wow!!! That's beautiful. Thank you very much!



I think it's straightforward enough to be dealt with simply.  Here is
a solution that doesn't handle errors but should work with well-formed
input and handles recursive expansions.

expand(filename) returns an iterator over expanded lines in the file,
inserting lines of included files.

import re

def expand(filename):
    defines = {}
    def define_repl(matchobj):
        return defines[]
    define_regexp = re.compile('#(.+?)#')
    for line in open(filename):
        if line.startswith('#include '):
           recfilename = line.strip().split(None, 1)[1]
           for recline in expand(recfilename):
               yield recline
        elif line.startswith('#define '):
           _, name, value = line.strip().split(None, 2)
           defines[name] = value
            yield define_regexp.sub(define_repl, line)

It would be easy to modify it to keep track of line numbers and file


More information about the Python-list mailing list