0

我正在调查内存泄漏,并且正在寻找一种遍历对象的方法。我想出了以下代码。

def obj_scan(obj, path, fname):
    def _store(msg):
        open(fname, 'a').write(path+msg+'\n')

    try:
        if callable(obj):
            return
        obj_type = type(obj)
        if obj_type is str:
            _store('- STR {}'.format(len(obj)))
        elif obj is None:
            _store('- NONE')
        elif obj_type is int:
            _store('- INT')
        elif obj_type is list:
            for idx, val in enumerate(obj):
                obj_scan(val, '{}[{}]'.format(path, idx), fname)
        elif obj_type is dict:
            for key, val in obj.iteritems():
                fmt_line = '{}['+('"{}"]' if type(key) is str else ']')
                obj_scan(val, fmt_line.format(path, key), fname)
        else:
            for attr in dir(obj):
                if ('.'+attr) in path and attr != '__dict__':
                    count = path.count('.'+attr)+1
                    _store('.{} - ATTR repeated {}{}'.format(attr, count, ' - BACTRACKING'*(count>10)))
                    if count>10:
                        return
                obj_scan(getattr(obj, attr), '{}.{}'.format(path, attr), fname)
    except Exception as msg:
        _store('Recursion limit exceeded')

我的问题是 - 有没有更有效的方法来做到这一点?(我知道 - 输出不会赢得选美比赛)

4

0 回答 0