Skip to main content
 首页 » 编程设计

python之如何使用 gitpython 获取提交作者姓名和电子邮件

2025年05月04日32zhengyun_ustc

当我运行 git log 时,每次提交都会得到这一行:“Author: name < email >”。如何在 Python 中为本地存储库获取完全相同的提交格式?当我运行下面的代码时,我只得到作者姓名。

from git import Repo 
 
repo_path = 'mockito' 
repo = Repo(repo_path) 
 
commits_list = list(repo.iter_commits()) 
 
for i in range(5): 
    commit = commits_list[i] 
 
    print(commit.hexsha) 
    print(commit.author) 
    print(commit.committer) 

请您参考如下方法:

似乎 gitpython 的 Commit 对象没有作者电子邮件的属性。

你也可以使用 gitpython 来 call git commands directly .您可以使用 git show命令,传入提交 HASH(来自 commit.hexsha),然后是 --format仅提供作者姓名和电子邮件的选项(您当然可以传递所需的其他格式选项)。

使用纯 git:

$ git show -s --format='%an <%ae>' 4e13ccfbde2872c23aec4f105f334c3ae0cb4bf8 
me <me@somewhere.com> 

使用 gitpython 来 use git directly :

from git import Repo 
 
repo_path = 'myrepo' 
repo = Repo(repo_path) 
 
commits_list = list(repo.iter_commits()) 
for i in range(5): 
    commit = commits_list[i] 
 
    author = repo.git.show("-s", "--format=Author: %an <%ae>", commit.hexsha) 
    print(author)