Python操作Git库 `GitPython`

Python017

Python操作Git库 `GitPython`,第1张

参考文章

参考文章

复杂点的参考

试了一圈发现,git库的用法设置非常符合原生git命令,只不过之间加了个 . 而已。

比如原本命令行里是 git add . ,这里就是 repo.git.add('.') ,

原本是 git commit -m "信息" ,这里就是 repo.git.commit(m='信息')

可以说减少了很多学习时间,基本上我很多都是没参考文档自己猜出来的也能用。

库安装好后可以直接在python中用了。

文件夹地址可以是全路径,也可以是 . 当前文件夹、 ../ 上级文件夹等用法。

直接执行

下面是一种解决方案

1 把gitbash 的路径放到系统的Path环境变量里 我的是 C:\Program Files (x86)\Git\bin

2 这时候 你在系统命令行里就可以用git了

3 在python里倒入 os 模块 然后执行

os.system('git') 就可以了

C:\Users\Administrator>python

Python 2.7.8 (default, Jun 30 2014, 16:08:48) [MSC v.1500 64 bit (AMD64)] on win3

Type "help", "copyright", "credits" or "license" for more information.

>>> import os

>>> os.system('git')

usage: git [--version] [--help] [-C <path>] [-c name=value]

           [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]

           [-p|--paginate|--no-pager] [--no-replace-objects] [--bare]

           [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]

           <command> [<args>]

The most commonly used git commands are:

   add        Add file contents to the index

   bisect     Find by binary search the change that introduced a bug

   branch     List, create, or delete branches

   checkout   Checkout a branch or paths to the wo

1:首先在本地新建一个文件夹,比如名字是E:\Python代码\Git关联Pycharm项目\MyNowCoder_C1(这个是该文件夹的绝对路径)

2:为了使Git管理该文件夹,还需要做一件事情,在当前文件下面打开,gitBash,数入命令 git init 即可,这个时候会生成一个.git的隐藏文件,这就说明,git已经可以管理这个文件夹了.

3:然后创建一个记事本文件,readme.txt,随便在里面写上几句话,用来测试,使用命令 git add readme.txt 将该文件添加到暂存区里面去,如果没有任何提示,说明操作成功了。

4:接下来使用命令,git commit 告诉git ,把文件提交到仓库,使用命令 git commit -m "这里写的是提交的注释" 回车.