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 次, 推送成功