使用Python腳本執(zhí)行Git命令的操作步驟
說明:本文介紹如何使用Python腳本在某個目錄下執(zhí)行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}'
# 執(zhí)行
subprocess.run(
[git_bash_paths, "-c", full_command],
check=True # 如果命令返回非零狀態(tài)碼,則拋出異常
)
print(f"【命令在 '{folder_path}' 中成功執(zhí)行】")
print("==========================================================================")
except subprocess.CalledProcessError as e:
print(f"命令執(zhí)行失敗,返回碼: {e.returncode}")
except FileNotFoundError as e:
print(f"無法啟動 Git Bash: {e}")
except Exception as e:
print(f"發(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' 開頭,但仍將嘗試執(zhí)行。")
# 執(zhí)行
open_git_bash_and_run_command(folder_path, git_command_template)
其中,加上需要執(zhí)行的目錄
# 項目路徑
folder_path = r"C:\Users\10765\Documents\info\code\now\easyexcel"
加上電腦上安裝的 Git 執(zhí)行程序的地址
# Git Bash 的常見安裝路徑
git_bash_paths = r"C:\Program Files\Git\bin\bash.exe"
執(zhí)行,展示該目錄下執(zhí)行 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}'
# 執(zhí)行
subprocess.run(
[git_bash_paths, "-c", full_command],
check=True # 如果命令返回非零狀態(tài)碼,則拋出異常
)
print(f"【命令在 '{folder_path}' 中成功執(zhí)行】")
print("==========================================================================")
except subprocess.CalledProcessError as e:
print(f"命令執(zhí)行失敗,返回碼: {e.returncode}")
except FileNotFoundError as e:
print(f"無法啟動 Git Bash: {e}")
except Exception as e:
print(f"發(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' 開頭,但仍將嘗試執(zhí)行。")
# 循環(huán)執(zhí)行
for i in folder_path:
open_git_bash_and_run_command(i, git_command)
其中,get_weekdays_of_current_week() 用于計算本周的日期,git 命令中包含雙引號的用 .format() 替換,執(zhí)行效果如下,本周沒有日志

python 腳本在 windows 系統(tǒng)中的好處是能和 bat 程序一樣,直接雙擊運行,因此如果工作中有需要定期執(zhí)行 git 命令的場景,可以使用寫一個 python 腳本,再配置環(huán)境變量,最后就能直接在運行中敲程序文件名執(zhí)行,非常方便。
如下:
給腳本所在的文件夾配置了環(huán)境變量后,敲腳本文件名執(zhí)行

彈出展示執(zhí)行結果

需要注意在程序末尾加這一行,不然執(zhí)行窗口會一閃而過

到此這篇關于使用Python腳本執(zhí)行Git命令的操作步驟的文章就介紹到這了,更多相關Python腳本執(zhí)行Git命令內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
創(chuàng)建虛擬環(huán)境打包py文件的實現步驟
使用虛擬環(huán)境,可以為每個項目創(chuàng)建一個獨立的Python環(huán)境,每個環(huán)境都有自己的庫和版本,從而避免了依賴沖突,本文主要介紹了創(chuàng)建虛擬環(huán)境打包py文件的實現步驟,感興趣的可以了解一下2024-04-04
PyTorch?Dataset與DataLoader使用超詳細講解
用于處理數據樣本的代碼可能會變得凌亂且難以維護;理想情況下,我們希望數據集代碼與模型訓練代碼解耦,以獲得更好的可讀性和模塊化。PyTorch提供的torch.utils.data.DataLoader和torch.utils.data.Dataset允許你使用預下載的數據集或自己制作的數據2022-10-10

