實現自動git push的python腳本

前言

我想用python腳本實現自動push,首先我有一個完整的code但是我想每天都運行一次,並將運行之後項目的改變進行 push 更新。
解決思路:

  1. 模擬 git add/commit -m/push 的過程
  2. 解決免密push的問題
  3. 整合需求編寫代碼

開始介紹前,先設置好自己的賬號和郵箱(做好準備)

git config --global user.name <YourName>
git config --global user.email <YourEmail>

gitpython

gitpython是git版本控制庫的python版本,可以通過它實現git的任何操作,十分方便

安裝

pip install gitpython

調用 | 例子

在項目根目錄下創建這個文件

from git import Repo
import os

dirfile = os.path.abspath('') # code的文件位置,我默認將其存放在根目錄下
repo = Repo(dirfile)

g = repo.git
g.add("--all")
g.commit("-m auto update")
g.push()
print("Successful push!")

Code on python shell

在這裏插入圖片描述
通過git status 也可以觀察到,我們添加了test文件,現在我就用python shell實現git push
在這裏插入圖片描述
ps: 需要注意的是,如果沒有設置免密,是會彈出登錄頁面的(就和命令行操作一樣),但是在code中沒辦法輸入賬號密碼啊,所以需要設置免密。

輸入賬號密碼之後,查看代碼庫提交記錄
在這裏插入圖片描述
提交成功!!!

關於gitpython的更多詳細內容

官網手冊

os

os庫可以稱爲萬能庫,因爲git add/commit -m/push 一般都是在命令行中完成的
只要引用os.system(’’) 即可實現需求

Code on python shell

只要通過os.system(’’)調用命令即可。下面就通過os庫刪除test文件並提交push
在這裏插入圖片描述

實現免密登錄的方法

配置SSH-key

  1. 生成key
ssh-keygen -t rsa -C "github賬號的郵箱"
  1. 複製rsa.pub(public key 公鑰)的內容
  2. 將public key添加到github上

參考資料:

https://blog.csdn.net/SJ1551/article/details/100745846
https://help.github.com/en/github/authenticating-to-github/connecting-to-github-with-ssh
https://www.jianshu.com/p/28efda0555bb

.gitconfig設置記住密碼

  1. 執行命令,配置 user.name 和 user.email
git config --global user.name <YourName>
git config --global user.email <YourEmail>
  1. 配置免密登入信息
# 寫入緩存,實現暫時記住賬號密碼(15分鐘)
git config --global credential.helper cache

# 寫入磁盤, 永久記住密碼
git config --global credential.helper store

我配置的是第二個,查看~/.gitconfig 的內容爲
Win的.gitconfig位置在 C:<balabala>\Administrator\下

[user]
    name = <YourName>
    email = <YourEmail>

[credential]
    helper = store
  1. push一次,配置後的第一次push需要登入,之後就會記住密碼實現免密push
  2. 取消免密登錄
sudo git config --system --unset credential.helper

關於作者

聯繫方式 MTI5MDAxNzU1NkBxcS5jb20=

你也可以通過 github | csdn | @新浪微博 關注我的動態

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章