使用Python脚本执行Git命令的操作步骤
作者:何中应
大家好,当谈及版本控制系统时,Git是最为广泛使用的一种,而Python作为一门多用途的编程语言,在处理Git仓库时也展现了其强大的能力,在本文中,我们将探讨如何使用Python脚本执行Git命令,需要的朋友可以参考下
说明:本文介绍如何使用Python脚本在某个目录下执行Git命令
编码
直接上代码
import os import subprocess def open_git_bash_and_run_command(folder_path, git_command): # 检查文件夹路径是否存在 if not os.path.exists(folder_path): print(f"错误:文件夹路径不存在:{folder_path}") return if not os.path.isdir(folder_path): print(f"错误:路径不是一个文件夹:{folder_path}") return # Git Bash 的常见安装路径 git_bash_paths = r"" try: full_command = f'cd "{folder_path}" && {git_command}' # 执行 subprocess.run( [git_bash_paths, "-c", full_command], check=True # 如果命令返回非零状态码,则抛出异常 ) print(f"【命令在 '{folder_path}' 中成功执行】") print("==========================================================================") except subprocess.CalledProcessError as e: print(f"命令执行失败,返回码: {e.returncode}") except FileNotFoundError as e: print(f"无法启动 Git Bash: {e}") except Exception as e: print(f"发生未知错误: {e}") if __name__ == "__main__": # 项目路径 folder_path = r"" # Git 命令,用三引号转义 git_command_template = """git status""" # Git 命令校验,以 git 开头 if not git_command_template.lower().startswith("git "): print("警告:命令似乎不是以 'git' 开头,但仍将尝试执行。") # 执行 open_git_bash_and_run_command(folder_path, git_command_template)
其中,加上需要执行的目录
# 项目路径 folder_path = r"C:\Users\10765\Documents\info\code\now\easyexcel"
加上电脑上安装的 Git 执行程序的地址
# Git Bash 的常见安装路径 git_bash_paths = r"C:\Program Files\Git\bin\bash.exe"
执行,展示该目录下执行 Git 命令 git status
的返回结果
更近一步
来点难度的,查看多个 Git 文件夹本周一~周五的日志记录,git 命令如下:
git log --since="2025-08-25" --until="2025-08-29"
代码如下:
import os import subprocess from datetime import datetime, timedelta def open_git_bash_and_run_command(folder_path, git_command): # 检查文件夹路径是否存在 if not os.path.exists(folder_path): print(f"错误:文件夹路径不存在:{folder_path}") return if not os.path.isdir(folder_path): print(f"错误:路径不是一个文件夹:{folder_path}") return # Git Bash 的常见安装路径 git_bash_paths = r"C:\Program Files\Git\bin\bash.exe" try: full_command = f'cd "{folder_path}" && {git_command}' # 执行 subprocess.run( [git_bash_paths, "-c", full_command], check=True # 如果命令返回非零状态码,则抛出异常 ) print(f"【命令在 '{folder_path}' 中成功执行】") print("==========================================================================") except subprocess.CalledProcessError as e: print(f"命令执行失败,返回码: {e.returncode}") except FileNotFoundError as e: print(f"无法启动 Git Bash: {e}") except Exception as e: print(f"发生未知错误: {e}") def get_weekdays_of_current_week(): # 获取今天的日期 today = datetime.today() # 计算今天是星期几 (0=Monday, 1=Tuesday, ..., 6=Sunday) weekday = today.weekday() # 计算本周一的日期 # 用今天的日期减去 weekday 天,就得到周一 monday = today - timedelta(days=weekday) # 生成周一到周五的日期 weekdays = [] for i in range(5): # 0=Monday, 1=Tuesday, 2=Wednesday, 3=Thursday, 4=Friday day = monday + timedelta(days=i) # 格式化为 yyyy-MM-dd formatted_date = day.strftime("%Y-%m-%d") weekdays.append(formatted_date) return weekdays if __name__ == "__main__": # 项目路径 folder_path = [r"C:\Users\10765\Documents\info\code\now\yudao-cloud", r'C:\Users\10765\Documents\info\code\now\yudao-ui-admin-vue3'] # 计算日期,本周一~周五 week_dates = get_weekdays_of_current_week() # Git 命令 git_command_template = """git log --since={since} --until={until}""" # 使用 .format() 方法替换占位符 git_command = git_command_template.format(since=week_dates[0], until=week_dates[4]) # Git 命令校验,以 git 开头 if not git_command_template.lower().startswith("git "): print("警告:命令似乎不是以 'git' 开头,但仍将尝试执行。") # 循环执行 for i in folder_path: open_git_bash_and_run_command(i, git_command)
其中,get_weekdays_of_current_week()
用于计算本周的日期,git 命令中包含双引号的用 .format()
替换,执行效果如下,本周没有日志
python 脚本在 windows 系统中的好处是能和 bat 程序一样,直接双击运行,因此如果工作中有需要定期执行 git 命令的场景,可以使用写一个 python 脚本,再配置环境变量,最后就能直接在运行中敲程序文件名执行,非常方便。
如下:
给脚本所在的文件夹配置了环境变量后,敲脚本文件名执行
弹出展示执行结果
需要注意在程序末尾加这一行,不然执行窗口会一闪而过
到此这篇关于使用Python脚本执行Git命令的操作步骤的文章就介绍到这了,更多相关Python脚本执行Git命令内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!