网站首页 > 技术文章 正文
花下猫语: 今天,我在查阅如何用 Python 操作 Gitlab 的时候,看到这篇文章,觉得还不错,特分享给大家。文中还提到了其它几种操作 Git 的方法,后续有机会的话,再陆续分享之~~
作者:匿蟒
出处:
https://note.qidong.name/2018/01/gitpython
有时,需要做复杂的 Git 操作,并且有很多中间逻辑。 用 Shell 做复杂的逻辑运算与流程控制就是一个灾难。 所以,用 Python 来实现是一个愉快的选择。 这时,就需要在 Python 中操作 Git 的库。
GitPython 简介
GitPython是一个与Git库交互的Python库,包括底层命令(Plumbing)与高层命令(Porcelain)。 它可以实现绝大部分的Git读写操作,避免了频繁与Shell交互的畸形代码。 它并非是一个纯粹的Python实现,而是有一部分依赖于直接执行git命令,另一部分依赖于GitDB。
GitDB也是一个Python库。 它为.git/objects建立了一个数据库模型,可以实现直接的读写。 由于采用流式(stream)读写,所以运行高效、内存占用低。
GitPython安装
pip install GitPython
其依赖GitDB会自动安装,不过可执行的git命令需要额外安装。
基本用法
init
import git repo = git.Repo.init(path='.')
这样就在当前目录创建了一个Git库。 当然,路径可以自定义。
由于git.Repo实现了__enter__与__exit__,所以可以与with联合使用。
with git.Repo.init(path='.') as repo: # do sth with repo
不过,由于只是实现了一些清理操作,关闭后仍然可以读写,所以使用这种形式的必要性不高。 详见附录。
clone
clone分两种。 一是从当前库clone到另一个位置:
new_repo = repo.clone(path='../new')
二是从某个URL那里clone到本地某个位置:
new_repo = git.Repo.clone_from(url='git@github.com:USER/REPO.git', to_path='../new')
commit
with open('test.file', 'w') as fobj: fobj.write('1st line\n') repo.index.add(items=['test.file']) repo.index.commit('write a line into test.file') with open('test.file', 'aw') as fobj: fobj.write('2nd line\n') repo.index.add(items=['test.file']) repo.index.commit('write another line into test.file')
status
GitPython并未实现原版git status,而是给出了部分的信息。
>>> repo.is_dirty() False >>> with open('test.file', 'aw') as fobj: >>> fobj.write('dirty line\n') >>> repo.is_dirty() True >>> repo.untracked_files [] >>> with open('untracked.file', 'w') as fobj: >>> fobj.write('') >>> repo.untracked_files ['untracked.file']
checkout(清理所有修改)
>>> repo.is_dirty() True >>> repo.index.checkout(force=True) <generator object <genexpr> at 0x7f2bf35e6b40> >>> repo.is_dirty() False
branch
获取当前分支:
head = repo.head
新建分支:
new_head = repo.create_head('new_head', 'HEAD^')
切换分支:
new_head.checkout() head.checkout()
删除分支:
git.Head.delete(repo, new_head) # or git.Head.delete(repo, 'new_head')
merge
以下演示如何在一个分支(other),merge另一个分支(master)。
master = repo.heads.master other = repo.create_head('other', 'HEAD^') other.checkout() repo.index.merge_tree(master) repo.index.commit('Merge from master to other')
remote, fetch, pull, push
创建remote:
remote = repo.create_remote(name='gitlab', url='git@gitlab.com:USER/REPO.git')
远程交互操作:
remote = repo.remote() remote.fetch() remote.pull() remote.push()
删除remote:
repo.delete_remote(remote) # or repo.delete_remote('gitlab')
其它
其它还有Tag、Submodule等相关操作,不是很常用,这里就不介绍了。
GitPython的优点是在做读操作时可以方便地获取内部信息,缺点是在做写操作时感觉很不顺手,隔靴搔痒。 当然,它还支持直接执行git操作。
git = repo.git git.status() git.checkout('HEAD', b="my_new_branch") git.branch('another-new-one') git.branch('-D', 'another-new-one')
这……感觉又回到了老路,而且仍然感觉怪怪的。
其它操作Git的方法
subprocess
这就是所谓『老路』。 在另一个进程,执行Shell命令,并通过stdio来解析返回结果。
import subprocess subprocess.call(['git', 'status'])
dulwich
dulwich是一个纯Python实现的Git交互库,以后有空再研究吧。
官方网站:https://www.dulwich.io/
pygit2
pygit2是基于libgit2实现的一个Python库。 底层是C,而上层Python只是接口,运行效率应该是最高的,然而孤还是放弃了。 其缺点是,需要环境中预先安装libgit2。 相比之下,GitPython只需要环境预置Git,简单多了。
官方网站:http://www.pygit2.org/
参考
- 《GitPython Documentation》
- 《Welcome to GitDB’s documentation!》
- 《Git - 底层命令 (Plumbing) 和高层命令 (Porcelain)》
- 《GitPython | Hom》
附录
在git.Repo中对context相关接口的实现如下:
def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.close() def __del__(self): try: self.close() except: pass def close(self): if self.git: self.git.clear_cache() gc.collect() gitdb.util.mman.collect() gc.collect()
可见只是一些清理操作,关闭的必要性不高。 即使关闭,也仍然可以对这个git.Repo的instance进行读写操作。
- 上一篇: 一行代码可以做什么?Python给你答案
- 下一篇: 你应该知道的 50 个 Python 单行代码
猜你喜欢
- 2025-05-11 5 个让代码更干净、更高效的 Python 好习惯
- 2025-05-11 掌握5 个 Python关键程序,编写更清晰、更高效的代码
- 2025-05-11 10个Python单行代码技巧,快速搞定数据清洗
- 2025-05-11 你应该知道的 50 个 Python 单行代码
- 2025-05-11 一行代码可以做什么?Python给你答案
- 2025-05-11 应该要看的十条单行Python代码
- 2025-05-11 10 个 Python 单行代码搞定 Scikit-learn 任务,效率提升 80%!
- 2025-05-11 6行Python代码实现进度条效果(tqdm,Progress)
- 2025-05-11 Python进阶-day20: 代码风格与工具
- 2025-05-11 需要知道12 个 Python 单行代码1
- 05-27程序员用 Python 爬取抖音高颜值美女
- 05-27YOLO v3、FaceNet和SVM的人脸检测识别系统源码(python)分享
- 05-27「工具推荐」世界上最简单的人脸识别库 44.7 star
- 05-27开源人脸识别系统源码推荐
- 05-27Go 人脸识别教程
- 05-27Python 深度学习之人脸识别(yolo+facenet)
- 05-27简单的Py人脸识别
- 05-27Python编程 - 基于OpenCV实现人脸识别(实践篇)爬虫+人脸识别
- 257℃Python短文,Python中的嵌套条件语句(六)
- 257℃python笔记:for循环嵌套。end=""的作用,图形打印
- 256℃PythonNet:实现Python与.Net代码相互调用!
- 251℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 251℃Python实现字符串小写转大写并写入文件
- 106℃原来2025是完美的平方年,一起探索六种平方的算吧
- 91℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 82℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)