2015-07-21 228 views
1

我對git很陌生,但我試圖用python來檢查git存儲庫是否有任何未提交的更改。無論我嘗試使用python運行什麼命令,我似乎都會得到相同的錯誤。這裏是我的代碼:如何使用Python檢查Git Repo是否有未提交的更改

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。任何幫助將不勝感激!

回答

1

在您的特定示例中(僅用於說明目的),您的"path\to\my\repo"將被理解爲'path\to\\my\repo'。在路徑的組件之間使用雙反斜槓("path\\to\\my\\repo")。 \t被理解爲一個選項卡,並且\r被理解爲回車符。或者,您可以在路徑前面輸入r,如下所示:r"path\to\my\repo"

+0

這些「[string lterals](https://en.wikipedia.org/wiki/String_literal)」被稱爲原始字符串,但請記住,這只是表示程序文本中字符串的一種不同方式 - t表示不同類型的對象。 – holdenweb

+0

@holdenweb感謝您爲jtaylor解釋。如果在Python 3之前使用'u'而不是'r',那麼數據類型將會不同。在Python 3之後,用'b'代替'r'也會改變數據類型。 –

1

看起來像GitPython找不到git.exe。

嘗試設置環境變量GIT_PYTHON_GIT_EXECUTABLE。 這是應該最有可能是 「C:\ Program Files文件(x86)的\的Git \ BIN \ git.exe」 如果使用混帳的Windows與默認

在命令行(CMD.EXE)

set GIT_PYTHON_GIT_EXECUTABLE="C:\Program Files (x86)\Git\bin\git.exe" 
0
from git import Repo 
def has_uncommited(repo_path): 
    repo = Repo(repo_path) 
    untracked = repo.untracked_files 
    return untracked is None 

會做你想要什麼,根據documentation,反正。

1

感謝您的建議,但實施它們並沒有真正解決我的問題。只要

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 = repo.head.commit.committed_datelastCommit說法這應該很好地工作:我沒有制定變通用下面的代碼。

相關問題