GitPython模块简介

copy from :https://blog.csdn.net/lwcaiCSDN/article/details/89382242

 

一 简介
1.作用

GitPython块python用来封装git操作的模块,主要用来替代gitbash的操作。

2.安装

直接pip install gitpython即可,使用的时候import git

依赖:

Python 2.7 or newer
Git 1.7.0 or newer
It should also work with older versions, but it may be that some operations involving remotes will not work as expected.
GitDB - a pure python git database implementation
Python Nose - used for running the tests
Mock by Michael Foord used for tests. Requires version 0.5
二 使用
1.Repo对象

GitPython的所有git操作都是通过Repo对象来操作的,获取该对象的方式有三种:


# 选择已有仓库
repo = git.Repo('仓库地址')

# 在文件夹里新建一个仓库,如果已存在git仓库也不报错不覆盖没问题
repo = git.Repo.init(path='文件夹地址')

# 克隆仓库
repo = git.Repo.clone_from(url='git@github.com:USER/REPO.git', to_path='../new')
2.暂存区对象

index = repo.index # 获取暂存区对象
index.add(['new.txt']) # add操作
index.remove(['old.txt']) # 删除暂存区对象
index.commit('this is a test') # 提交
3.创建远程对象remote

# 创建remote:
remote = repo.create_remote(name='gitlab', url='git@gitlab.com:USER/REPO.git')

# 如果是通过clone下载的项目可直接通过repo.remote()创建remote对象
remote = repo.clone_from(git_url, to_path).remote()

# 远程交互:
remote = repo.remote()
remote.fetch()
remote.pull()
remote.push()
 4.直接执行原生命令

git = repo.git # 通过Repo对象获取git对象
git.add('test1.txt') # git add test1.txt
git.commit('-m', 'this is a test') # git commit -m 'this is a test'
备注: 这里要注意一点原生的git命令会有两种参数形式,一种是:命令 --参数关键字 参数;一种是:命令 --参数关键字=参数;这两种转化时要用如下形式,总之空格要用逗号区分,并且注意顺序:

# 第一种情况
repo.git.reset("--hard", "3ab65we")

# 第二中情况
repo.git.log("--date=short", "--pretty=format:%H:%h:%an:%ad:%cd:%cn:%s")
————————————————
版权声明:本文为CSDN博主「lwcaicsdn」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/lwcaiCSDN/article/details/89382242

posted @ 2020-02-13 18:44  oude_yang  阅读(632)  评论(0编辑  收藏  举报