在日常开发中,我们经常需要频繁地向 Git 仓库提交代码。虽然 git add、git commit、git push 这几个命令并不复杂,但重复操作容易出错,也浪费时间。本文将介绍如何使用 Python 脚本自动化完成 Git 提交流程,让开发更高效!
我们将使用 Python 的 subprocess 模块来调用系统中的 Git 命令。脚本会依次执行以下操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
import subprocess import sys from datetime import datetime
def run_command(command): """ 执行系统命令并返回结果 :param command: 命令字符串或列表 :return: (成功标志, 输出信息) """ try: # 如果传入字符串,则分割成列表 if isinstance(command, str): command = command.split()
# 执行命令 result = subprocess.run(command, capture_output=True, text=True, check=True) return True, result.stdout.strip() except subprocess.CalledProcessError as e: return False, f"命令执行失败: {e.stderr.strip()}" except Exception as e: return False, f"未知错误: {str(e)}"
def git_auto_commit(commit_message=None): """ 自动化Git提交 :param commit_message: 提交信息,若为空则使用默认信息 """ print("???? 开始自动化Git提交流程...\n")
# 1. 检查是否在Git仓库中 success, output = run_command("git status") if not success: print("? 错误: 当前目录不是Git仓库或Git未安装。") print(output) return print("? 检测到Git仓库,状态检查通过。")
# 2. 获取当前分支信息 success, branch = run_command("git branch --show-current") if success: print(f"???? 当前分支: {branch}") else: print("?? 无法获取分支信息。")
# 3. 添加所有变更文件 print("\n???? 正在添加所有变更文件到暂存区...") success, output = run_command("git add .") if not success: print(f"? 文件添加失败: {output}") return print("? 所有文件已添加。")
# 4. 构造提交信息 if not commit_message: commit_message = f"Auto-commit from Python script on {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
# 5. 执行提交 print(f"\n???? 正在提交变更: {commit_message}") success, output = run_command(["git", "commit", "-m", commit_message]) if not success: # 如果没有变更需要提交,git commit 会失败,但这是正常情况 if "nothing to commit" in output: print("? 仓库已是最新,无需提交。") # 仍然继续推送,以防有新的标签或其他更新 else: print(f"? 提交失败: {output}") return else: print("? 提交成功!")
# 6. 推送到远程仓库 print("\n???? 正在推送到远程仓库...") success, output = run_command("git push") if not success: print(f"? 推送失败: {output}") print("???? 请检查网络连接、远程仓库地址和认证信息(如SSH密钥或Token)。") return
print("? 推送成功!") print(f"\n???? 自动化提交流程已完成!")
# 7. 显示最终状态 print("\n???? 最终仓库状态:") success, status = run_command("git status --short") if success: if status: print("?? 以下文件未跟踪或有未提交的更改:") print(status) else: print("? 仓库状态干净,所有更改已提交并推送。") else: print("无法获取最终状态。")
if __name__ == "__main__": # 可以从命令行参数获取提交信息 message = None if len(sys.argv) > 1: message = " ".join(sys.argv[1:])
git_auto_commit(message) |
1.保存代码:将上述代码保存为 auto_git.py。
2.确保环境:
3.运行脚本:
使用默认提交信息:
1 |
python auto_git.py |
指定自定义提交信息:
1 |
python auto_git.py "修复了登录页面的样式问题" |
???? 开始自动化Git提交流程...
? 检测到Git仓库,状态检查通过。
???? 当前分支: main
???? 正在添加所有变更文件到暂存区...
? 所有文件已添加。
???? 正在提交变更: Auto-commit from Python script on 2025-07-29 16:45:30
? 提交成功!
???? 正在推送到远程仓库...
? 推送成功!
???? 自动化提交流程已完成!
???? 最终仓库状态:
? 仓库状态干净,所有更改已提交并推送。
安全性:此脚本直接执行系统命令,请确保在可信环境中运行。
错误处理:脚本包含了基本的错误处理,但复杂情况(如合并冲突)仍需手动干预。
凭证:首次推送或凭证过期时,Git 可能会提示输入用户名/密码或使用 SSH 密钥。建议配置 SSH 免密或使用 Personal Access Token。
灵活性:你可以根据需要修改 git add . 为更精确的路径,或者添加 git pull 在推送前先拉取更新。
这个简单的 Python 脚本可以大大简化你的 Git 提交流程,特别适合于需要频繁提交小改动的场景(如笔记、文档更新)。你可以将其集成到 IDE、编辑器或作为定时任务运行,进一步提升开发效率!