简体   繁体   English

如何遍历 python 目录并在 root 处停止一次

[英]How can you loop through python directories and stop once at root

In Python, I'm using a while loop to test whether the CWD is a git repository.在 Python 中,我使用while循环来测试 CWD 是否是 git 存储库。 If it's not, the CWD is changed ( .. ) and tested again.如果不是,则更改 CWD ( .. ) 并再次测试。

If a git repository is found then the function works as expected.如果找到 git 存储库,则该函数按预期工作。 However, if no git repository is found, the while loop keeps going because os.chdir('..') doesn't generate an error, even if the CWD is at / .但是,如果没有找到 git 存储库, while循环会继续运行,因为os.chdir('..')不会生成错误,即使 CWD 位于/

def get_git_repo():
    path = os.getcwd()
    original_path = path
    is_git_repo = False
    while not is_git_repo:
        try:
            repo = git.Repo(path).git_dir
            is_git_repo = True
        except git.exc.InvalidGitRepositoryError:
            is_git_repo = False
            path = os.chdir('..')
    os.chdir(original_path)
    return repo

To try and fix this, I added a test to check if the CWD is / , but that doesn't work and the while loop still carries on forever.为了尝试解决这个问题,我添加了一个测试来检查 CWD 是否为/ ,但这不起作用并且while循环仍然会一直持续下去。

How can I bail out of the function once the CWD is / , and is not a git repository?一旦 CWD 是/并且不是 git 存储库,我该如何退出该函数?

def get_git_repo():
    ...
        except git.exc.InvalidGitRepositoryError:
            is_git_repo = False
            if not path == '/':
                path = os.chdir('..')
            else:
                raise Exception("Unable to discover path to git repository.")
    ...

the problem of your code is that os.chdir('..') return None , not the current path.您的代码的问题是os.chdir('..')返回None ,而不是当前路径。

You need to get the current dir after the change:您需要在更改后获取当前目录:

os.chdir('..')
path = os.getcwd()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM