如何模拟linux的find命令的`maxdepth`选项到python

时间:2017-04-27 10:05:13

标签: python linux python-3.x

我想在linux中为maxdepth选项提供标准的python解决方案。我可以使用find模拟os.walk()命令,但我想限制代码级别的深度。我不想在我的代码中使用subprocessPopen

1 个答案:

答案 0 :(得分:0)

您可以递归迭代所有路径,直到达到某个深度。这个解决方案不是特别有效,但它应该让你入门(需要Python 3.3或更高版本):

def find(path, maxdepth=-1, depth=0):
    path = "%s/" % path if path[-1] != "/" else path
    for f in os.listdir(path):
        p = "%s%s" % (path, f)
        yield p
        try:
            if (depth < maxdepth or maxdepth == -1) and os.path.isdir(p):
                yield from find(p, maxdepth, depth + 1)
        except OSError:
            pass

用法:

find(path, maxdepth)
# maxdepth=-1 means infinite depth (default)