[SOLVED] Python: Recursion and Generators

Status
Not open for further replies.
I've been trying to wrap my head around this problem for three days and can't figure it out.

I'm creating a disk usage analyzer that will create a weekly report about disk use. I have created a class that, given a parent directory, will automatically recurse through all sub-directories and create the information that I need. The class is called 'directory,' and contains a size attribute (size of all contained files/dirs), a full path name for the directory, and a list of 'directory' objects that are children to the current directory.

Basically I need to 'walk' through my tree of directories to sort by size and such. Currently, I'm trying to compile a short report on the top 10 directories by size. I need to walk through all the directories and return the path and size for each object.

The problem is that it's a weird mix of recursion and generation. A generator is very nice because I can do
Code:
for i in dir1.children:
    yield i.path, i.size
That works great for a given directory's children, but I can't down to the next level, which is where recursion should come in. I thought that I could do
Code:
for t in dir1.children:
    yield _topDirs(t)
where _topDirs(directory) is the generator function. However, that doesn't work.

Can anyone help me walk through my tree and yield values along the way?

Relevant code:

Code:
class directory:
    '''
    Class that automatically traverses directories
    and builds a tree with size info
    '''
    def __init__(self, path, parent=None):

        if path[-1] != '/':
            # Add trailing /
            self.path = path + '/'
        else:
            self.path = path
        self.size = 4096
        self.parent = parent
        self.children = []
        self.errors = []
        for i in os.listdir(self.path):
            try:
                self.size += os.lstat(self.path + i).st_size
                if os.path.isdir(self.path + i) and not os.path.islink(self.path + i):
                    a = directory(self.path + i, self)
                    self.size += a.size
                    self.children.append(a)
            except OSError:
                self.errors.append(path + i)
Code:
    def topDirs(dir1, N=5):
        '''
        Walks the tree and adds largest
        directories to a returned list.
        '''

        if type(dir1) == str:
            dir1 = directory(dir1)
        large = []
        for i in range(N):
            large.append(('', 0))
        for i, j in _topDirs(dir1):
            if j > large[-1][1]:
                large.append((i, j))
                large = sorted(large, key=lambda t: t[1], reverse=True)
                large.pop(-1)
        return large

    def _topDirs(dir1):
        '''
        Private function to walk the tree.
        '''
        for i in dir1.children:
            yield i.path, i.size
        for t in dir1.children:
            yield _topDirs(t)  # This doesn't work. How to recurse???

Thanks,
 

tuffy

Ars Scholae Palatinae
972
Is there a reason you're not using the os.walk function?

It sounds like it'll be easier to split this problem into two parts, one for recursively finding the size of a given root directory and another for finding all the subdirectories of a given root. Putting them both together should then give you the sizes you're looking for - assuming I understand the problem correctly.
 
tuffy":mpaaetwu said:
Is there a reason you're not using the os.walk function?

It sounds like it'll be easier to split this problem into two parts, one for recursively finding the size of a given root directory and another for finding all the subdirectories of a given root. Putting them both together should then give you the sizes you're looking for - assuming I understand the problem correctly.

os.walk() doesn't allow me to build a tree. I would have to re-scan the file system for every report I need create, which isn't acceptable. I'm working with a system that has ~620,000 directories.

I don't see how splitting into two parts will help. I will still need to walk through the tree, which is where I'm having problems.
 

tuffy

Ars Scholae Palatinae
972
If it's an optimization problem, then perhaps try forgoing the generator entirely and pass in an object for size accumulation, like:
Code:
def dir_sizes(basedir, accumulator):
    size = 4096

    for f in [os.path.join(basedir, l) for l in os.listdir(basedir)]:
        if (os.path.isfile(f)):
            size += os.path.getsize(f)
        elif (os.path.isdir(f)):
            size += dir_sizes(f, accumulator)
        else:
            #handle other types here
            pass

    accumulator.append((basedir, size))
    return size
Then just tweak the accumulation step to keep only the top N entries or something like that.
 

lostnihilist

Ars Scholae Palatinae
1,436
I believe you have run in to the reason for the creation of the "yield from" syntax:
http://www.python.org/dev/peps/pep-0380/

There are code samples there on what you need to do until that syntax is fully developed and supported. But basically, when you are doing recursive/nested yields, you need to loop over the recursed/nested call and yield each item individually.
 
Thanks for the responses tuffy, but I don't really understand what the accumulator is. Global list?

I've updated my code and stripped out as much as possible. I'm just trying to iterate through my tree.

I'm pretty sure that I'm doing almost correct, but I don't know how to handle 'generator' objects. I think that the problem might be because I'm nesting yield statements.

Code:
Code:
    def topDirs(dir1, N=20):
        if type(dir1) == str:
            dir1 = directory(dir1)
        for i in visit(dir1):
            print(i)
            time.sleep(1)

    def visit(dir1):
        yield dir1
        for i in dir1.children:
            yield visit(i)


Output:
<__main__.directory instance at 0x7f642e68e878>
<generator object visit at 0x1bf2a50>
<generator object visit at 0x1bf2aa0>
<generator object visit at 0x1bf2a50>
<generator object visit at 0x1bf2aa0>
<generator object visit at 0x1bf2a50>
<generator object visit at 0x1bf2aa0>
<generator object visit at 0x1bf2a50>
<generator object visit at 0x1bf2aa0>
<generator object visit at 0x1bf2a50>
<generator object visit at 0x1bf2aa0>
<generator object visit at 0x1bf2a50>
<generator object visit at 0x1bf2aa0>
<generator object visit at 0x1bf2a50>
<generator object visit at 0x1bf2aa0>
<generator object visit at 0x1bf2a50>
<generator object visit at 0x1bf2aa0>
<generator object visit at 0x1bf2a50>
<generator object visit at 0x1bf2aa0>
<generator object visit at 0x1bf2a50>
<generator object visit at 0x1bf2aa0>
That's not nearly enough output. I should get an object for every directory, and I'm searching /, so it's also stopping for some reason.
 

Alamout

Ars Legatus Legionis
27,285
visit() is yielding two different things, which is messing you up. First, it yields a directory object, then it yields a generator. You should change it so it always returns one type of thing, and it needs a base case so that it terminates.

Code:
def visit(dir1):
    if os.isdir(dir1):
        for j in os.listdir(dir1):
            for k in visit(os.path.join(dir1, j)):
                 yield k
    else:
        yield dir1

That'll do a DFS on your file structure, which might not be what you want.

edit: err, yeah, his thing is the same, but uses your directory class (FYI: classes are usually capitalized). Brain's not firing on all cylinders.
 
Status
Not open for further replies.