当前位置:首页>python>用Python操作GitHub:克隆、提交、推送一条龙

用Python操作GitHub:克隆、提交、推送一条龙

  • 2026-10-11 05:46:17
用Python操作GitHub:克隆、提交、推送一条龙

有没有遇到过这种情况:每次改完代码都要手动 git add、commit、push,或者需要批量操作一堆仓库但不想一个个敲命令?

其实用 Python 就能把这些事自动化。这篇文章分享一个轻量级的 GitPython 封装类,涵盖了日常开发中最常用的仓库操作——克隆、切换分支、修改文件、提交推送,一个类全搞定。

上代码 👇


🐍 GitPython 全套工具类

先安装依赖:

pip install gitpython
import osfrom git import Repoclass GitPython:    def __init__(self):        self.repo_url = 'https://github.com/xxxx'        self.local_path = '/home/user/xxx'    def clone_repo(self):        """克隆仓库"""        if not os.path.exists(self.local_path) or len(os.listdir(self.local_path)) == 0:            Repo.clone_from(self.repo_url, to_path=self.local_path, branch='master')    def get_branch(self):        """获取所有远程分支"""        repo = Repo(self.local_path)        branches = repo.remote().refs        for item in branches:            print(item.remote_head)    def checkout_branch(self):        """切分支 + 改文件 + 提交推送一条龙"""        repo = Repo(self.local_path)        remote = repo.remote()        # 基于 origin/dev 创建本地分支 dev/test3        repo.create_head('dev/test3', 'origin/dev')        repo.git.checkout('dev/test3')        print(f'当前分支: {repo.active_branch}')        # 拉取最新代码        remote.fetch()        remote.pull('dev')        # 创建或更新文件        demo = '/home/user/xxx/test.txt'        if not os.path.exists(demo):            os.system(f"touch {demo}")        repo.git.pull()        with open(demo, 'w') as f:            f.write('I am test.\n')            f.write('I am test pygithub.\n')        # 提交并推送        repo.index.add(items=[demo])        repo.index.commit('write another line into test.file')        remote.fetch()        remote.pull('dev')        remote.push(repo.active_branch)        # 切回 master,删除本地临时分支        repo.git.checkout('master')        repo.git.branch('-D', 'dev/test3')

📋 核心方法速查

                                                                                                               
方法作用关键 API
clone_repo()克隆远程仓库到本地(目录不存在时)Repo.clone_from()
get_branch()列出所有远程分支repo.remote().refs
checkout_branch()创建分支、切分支、改文件、提交推送、清理create_head / index.add / push

💡 几个实用小贴士

1. 路径判断要做好。 克隆前检查目录是否存在且非空,避免重复克隆覆盖已有代码。代码里用 os.path.exists + os.listdir 双重判断就很稳妥。

2. remote.fetch() 和 pull() 的区别。 fetch 只拉取不合并,pull = fetch + merge。如果你只想看看远端有什么变动但不想立刻合并,先用 fetch。

3. 临时分支用完就删。 工作流里常有"切个临时分支改点东西再合回去"的场景,记得切回主分支后 git.branch('-D', ...) 清理掉,保持仓库干净。

4. index.add() vs git.add()。 两种方式都能添加文件,repo.index.add() 更 Pythonic,repo.git.add() 更贴近命令行体验。看个人习惯选。


 📌 这份代码整理自知乎专栏,配合前面发的 Docker 速查和 Git 命令速查,日常开发的效率工具箱又补齐了一块。Python + Git + GitHub 这套组合,能帮你省掉大量重复操作。收藏起来,改天用得上~

—— 来自「三分技能铺」,用代码让生活更轻松

最新文章

随机文章