繁体   English   中英

如何使用Python检查Git Repo是否有未提交的更改

[英]How to check if a Git Repo has uncommitted changes using Python

我是git的新手,但是我试图使用python检查git存储库中是否有未提交的更改。 无论我尝试使用python运行什么命令,我似乎都会遇到相同的错误。 这是我的代码:

from git import *
repo = Repo("path\to\my\repo")
lastCommit = repo.head.commit.committed_date
uncommitted = repo.is_dirty()

一切正常,直到运行错误的最后一行为止:

Traceback (most recent call last):
.
.
.
    raise GitCommandNotFound: [Error 2] The system cannot find the file specified 

我也尝试了其他命令,但出现了同样的错误。 例如, repo.index.diff(repo.head.commit) 我也尝试过运行repo.index.diff(None)repo.index.diff('HEAD') ,它们给出相同的错误。 我真正想要的是实质上为我名为repo的存储库运行$ git status 我在Windows 7上使用的是Python 2.7.9和gitpython 1.0.1。不胜感激!

在您的特定示例(仅用于说明目的)中,您的"path\\to\\my\\repo"将被理解为'path\\to\\\\my\\repo' 在路径的各组成部分之间使用双反斜杠( "path\\\\to\\\\my\\\\repo" )。 \\t被理解为制表符, \\r被理解为回车符。 或者,您可以将r放在路径的前面,如下所示: r"path\\to\\my\\repo"

看起来GitPython找不到git.exe。

尝试设置环境变量GIT_PYTHON_GIT_EXECUTABLE 如果使用默认的Windows版Git,则最有可能是“ C:\\ Program Files(x86)\\ Git \\ bin \\ git.exe”

在命令行(cmd.exe)

set GIT_PYTHON_GIT_EXECUTABLE="C:\Program Files (x86)\Git\bin\git.exe"

感谢您的建议,但是实施它们并不能真正解决我的问题。 我确实使用以下代码开发了一种变通方法:

def statusChecker(repo, lastCommit):
    uncommittedFiles = []
    files = os.listdir(repo)
    for file in files:
        if os.path.getmtime(repo + "\\\\" + file) > lastCommit:
            uncommittedFiles.append(file)
    uncommittedFiles = uncommittedFiles.remove(".git")
    return uncommittedFiles

只要为lastCommit参数使用诸如lastCommit = repo.head.commit.committed_date的方法, lastCommit可以正常工作。

暂无
暂无

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

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