【问题标题】:How can you loop through python directories and stop once at root如何遍历 python 目录并在 root 处停止一次
【发布时间】:2021-11-12 11:51:35
【问题描述】:

在 Python 中,我使用 while 循环来测试 CWD 是否是 git 存储库。如果不是,则更改 CWD (..) 并再次测试。

如果找到 git 存储库,则该功能按预期工作。但是,如果没有找到 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

为了尝试解决这个问题,我添加了一个测试来检查 CWD 是否为 /,但这不起作用,while 循环仍然会一直持续下去。

一旦 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.")
    ...

【问题讨论】:

    标签: python working-directory


    【解决方案1】:

    你的代码的问题是os.chdir('..')返回None,而不是当前路径。

    更改后需要获取当前目录:

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

    【讨论】:

    • 啊,谢谢 - 这确实是我的问题。
    猜你喜欢
    • 2023-03-31
    • 1970-01-01
    • 2019-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多