通过Python脚本git push 自动重试推送代码


1.需求

由于网络等原因,推送到GitHub 仓库代码失败, 自动重试推送

技术: 采用 pexpect

2.脚本

retry_push.py

# -*- coding: utf-8 -*-
#!/usr/bin/python3

"""
pip3 install pexpect
"""

import pexpect
import os
import sys

time = 1
username = 'infuq'
password = 'qwert#123'


def retry():
    global time
    print('invoke retry %s time' % time)
    time = time + 1

    # 执行拉取
    spawner = pexpect.spawn('git push', encoding='utf-8')
    spawner.logfile = sys.stdout

    try:
        i = spawner.expect(['Everything up-to-date', 'Username']) # ,timeout = 10

        # 不需要输入用户名和密码的场景
        if i == 0:
            spawner.close()
            return

        # 需要输入用户名和密码的场景
        elif i == 1:
            # 输入用户名
            spawner.sendline(username)
            i = spawner.expect(['Password']) # ,timeout = 10
            if i == 0:
                # 输入密码
                spawner.sendline(password)
                i = spawner.expect(pexpect.EOF)
                if i == 0:
                    spawner.close()

                    status = spawner.status
                    exit_status = spawner.exitstatus
                    signal_status = spawner.signalstatus
                    # 正常退出场景
                    if exit_status == 0:                        
                        return
                    else:
                        # 异常退出场景, 重试
                        retry()
                else:
                    # 异常退出场景, 重试
                    retry()
            else:
                # 未出现输入密码的提示, 重试
                retry()
        else:
            # 未出现输入用户名的提示, 重试
            retry()
    except Exception:
        # 出现异常, 重试
        retry()


def main():
    # 进入到仓库目录
    os.chdir('/mnt/d/Repository/infuq-others')
    os.system('git add .')
    os.system('git commit -m "update"')
    retry()


if __name__ == '__main__':
    main()

3.执行脚本

[infuq ~]# python3 retry_push.py
[master 968c0ca] update
 1 file changed, 1 deletion(-)
invoke retry 1 time
invoke retry 2 time
Username for 'https://github.com': infuq
infuq
Password for 'https://infuq@github.com': qwert#123

Enumerating objects: 5, done.
Counting objects: 100% (5/5), done.
Delta compression using up to 2 threads
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 274 bytes | 274.00 KiB/s, done.
Total 3 (delta 2), reused 0 (delta 0)
remote: Resolving deltas: 100% (2/2), completed with 2 local objects.
To https://github.com/infuq/infuq-others.git
   70d7d61..968c0ca  master -> master


自动重试了 2 次, 推送成功


个人站点 https://www.infuq.com

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值