我結束了子流程路線。我不喜歡首先使用GitPython設置回購對象,因爲不能保證我的路徑甚至是git存儲庫的一部分。
對於那些有興趣,這裏是我結束了:
import subprocess
def git_check(path): # haha, get it?
# check if the file is in a git repository
proc = subprocess.Popen(['git',
'rev-parse',
'--is-inside-work-tree',],
cwd = path,
stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
if 'true' not in proc.communicate()[0]:
return None
# check the status of the repository
proc = subprocess.Popen(['git',
'status',],
cwd = path,
stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
log_lines = proc.communicate()[0].split('\n')
modified_files = [x.split(':')[1].lstrip() for x in log_lines if 'modified' in x]
new_files = [x.split(':')[1].lstrip() for x in log_lines if 'new file' in x]
# get log information
proc = subprocess.Popen(['git',
'log','-1'],
cwd = path,
stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
log_lines = proc.communicate()[0].split('\n')
commit = ' '.join(log_lines[0].split()[1:])
author = ' '.join(log_lines[1].split()[1:])
date = ' '.join(log_lines[2].split()[1:])
git_info = {'commit':commit,
'author':author,
'data': date,
'new files':new_files,
'modified files':modified_files}
return git_info
與GitPython肯定去:它應該允許使用Git的工作更直接,而不是解析一個命令行工具的輸出。 – janos