a problem with writing a generator

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Jan 14 09:49:08 EST 2010


On Thu, 14 Jan 2010 15:11:29 +0100, Paweł Banyś wrote:

> Hello,
> 
> Please forgive me if I repeat the subject anyhow. I am trying to write a
> simple program in Python which scans a config file in search for
> "include" lines. If those lines are found, the files included there are
> followed and scanned and if any further "include" lines are found, the
> whole procedure repeats itself. The program ends when the whole tree
> structure of those "includes" is generated.
> 
> I seem to have some blackout in my mind because I cannot understand how
> to use a generator functionality to complete the task. 

Do you have to use a generator? Just write the code in whatever way feels 
most comfortable to you. Generators aren't compulsory.

Anyway, here's an untested recursive generator solution that ignores 
everything but include lines, and yields the names of the files indented 
according to the depth of the structure.

def includes(filename, depth=0):
    yield "%s%s" % ("  "*depth, filename)
    f = open(filename, 'r')
    for line in f:
        if line.startswith('include '):
            inc, fname = line.split(None, 1)
            for line in includes(fname, depth=depth-1):
                yield line
    f.close()




-- 
Steven



More information about the Python-list mailing list