a problem with writing a generator
Lie Ryan
lie.1296 at gmail.com
Thu Jan 14 10:59:38 EST 2010
On 01/15/10 01:49, Steven D'Aprano wrote:
> 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()
that would always produce an empty file, no?
# another completely untested code; bugs may still be around
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
else:
yield line
f.close()
More information about the Python-list
mailing list