git庫的用法設置非常符合原生git命令,只不過之間加了個.
而已。
比如原本命令行裏是git add .
,這裏就是repo.git.add('.')
,
原本是git commit -m "信息"
,這裏就是repo.git.commit(m='信息')
安裝
pip3 install gitpython
創建、識別、克隆倉庫
文件夾地址可以是全路徑,也可以是.
當前文件夾、../
上級文件夾等用法。
import git
# 在文件夾裏新建一個倉庫,如果已存在git倉庫也不報錯不覆蓋沒問題
repo = git.Repo.init(path='文件夾地址')
# 選擇已有倉庫
repo = git.Repo( '倉庫地址' )
# 克隆倉庫 to_path是克隆後保存的文件位置地址,如果僅克隆下載可直接使用該方法
if os.listdir(savefilepath) == []:
repo = git.Repo.clone_from(url='[email protected]:USER/REPO.git', to_path='../new')
常用語句:
# 查看repo狀態
print repo.git.status() # 返回通常的status幾句信息
print repo.is_dirty() # 返回是否有改動(包括未add和未commit的)
# 添加文件 可以是單個文件名,也可以是`[ ]`數組,還可以是`.`代表全部
print repo.git.add( '文件名' )
# commit提交
print repo.git.commit( m='提交信息' )
遠程交互操作
# 創建remote:
remote = repo.create_remote(name='gitlab', url='[email protected]:USER/REPO.git')
# 遠程交互:
remote = repo.remote()
remote.fetch()
remote.pull()
remote.push()
實驗效果
# 原意是返回工作區是否改變的狀態
# 但是測試發現,工作區有變動它返回False,沒變動卻返回True
print repo.is_dirty()
生成tar壓縮包
# 壓縮到 tar 文件
with open('repo.tar', 'wb') as fp:
repo.archive(fp)