GitPython模块简介

3 篇文章 0 订阅

一 简介

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")

参考:

官网

使用 Python 操作 Git 版本库 - GitPython

 

  • 5
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值