实现自动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 | @新浪微博 关注我的动态

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