[SOLVED] Python: Recursion and Generators

Status
You're currently viewing only fandingo's posts. Click here to go back to viewing the entire thread.
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":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.
 
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.
 
Status
You're currently viewing only fandingo's posts. Click here to go back to viewing the entire thread.
Not open for further replies.