使用Python腳本執(zhí)行Git命令的操作步驟
說明:本文介紹如何使用Python腳本在某個(gè)目錄下執(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"錯(cuò)誤:文件夾路徑不存在:{folder_path}")
return
if not os.path.isdir(folder_path):
print(f"錯(cuò)誤:路徑不是一個(gè)文件夾:{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"無法啟動(dòng) Git Bash: {e}")
except Exception as e:
print(f"發(fā)生未知錯(cuò)誤: {e}")
if __name__ == "__main__":
# 項(xiàng)目路徑
folder_path = r""
# Git 命令,用三引號(hào)轉(zhuǎn)義
git_command_template = """git status"""
# Git 命令校驗(yàn),以 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í)行的目錄
# 項(xiàng)目路徑
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 的返回結(jié)果

更近一步
來點(diǎn)難度的,查看多個(gè) 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"錯(cuò)誤:文件夾路徑不存在:{folder_path}")
return
if not os.path.isdir(folder_path):
print(f"錯(cuò)誤:路徑不是一個(gè)文件夾:{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"無法啟動(dòng) Git Bash: {e}")
except Exception as e:
print(f"發(fā)生未知錯(cuò)誤: {e}")
def get_weekdays_of_current_week():
# 獲取今天的日期
today = datetime.today()
# 計(jì)算今天是星期幾 (0=Monday, 1=Tuesday, ..., 6=Sunday)
weekday = today.weekday()
# 計(jì)算本周一的日期
# 用今天的日期減去 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__":
# 項(xiàng)目路徑
folder_path = [r"C:\Users\10765\Documents\info\code\now\yudao-cloud",
r'C:\Users\10765\Documents\info\code\now\yudao-ui-admin-vue3']
# 計(jì)算日期,本周一~周五
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 命令校驗(yàn),以 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() 用于計(jì)算本周的日期,git 命令中包含雙引號(hào)的用 .format() 替換,執(zhí)行效果如下,本周沒有日志

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

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

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

到此這篇關(guān)于使用Python腳本執(zhí)行Git命令的操作步驟的文章就介紹到這了,更多相關(guān)Python腳本執(zhí)行Git命令內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用Python編寫一個(gè)簡(jiǎn)單易用的通用驗(yàn)證碼識(shí)別工具
在當(dāng)今的網(wǎng)絡(luò)環(huán)境中,驗(yàn)證碼(CAPTCHA)無處不在,如何高效地識(shí)別和處理這些驗(yàn)證碼卻是一個(gè)不小的挑戰(zhàn),下面我們就來看看如何使用ddddocr 編寫一個(gè)簡(jiǎn)單易用的通用驗(yàn)證碼識(shí)別工具吧2025-09-09
python時(shí)間與Unix時(shí)間戳相互轉(zhuǎn)換方法詳解
這篇文章主要介紹了python時(shí)間與Unix時(shí)間戳相互轉(zhuǎn)換方法詳解,需要的朋友可以參考下2020-02-02
Python全局變量與global關(guān)鍵字常見錯(cuò)誤解決方案
這篇文章主要介紹了Python全局變量與global關(guān)鍵字常見錯(cuò)誤解決方案,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-10-10
詳解MySQL數(shù)據(jù)類型int(M)中M的含義
int(M)拆分來說,int是代表整型數(shù)據(jù)那,么中間的M應(yīng)該是代表多少位了,后來查mysql手冊(cè)也得知了我的理解是正確的,下面這篇文章小編就來舉例詳細(xì)說明。 文中介紹的很詳細(xì),相信對(duì)大家的理解和學(xué)習(xí)很有幫助,有需要的朋友們下面就來學(xué)習(xí)學(xué)習(xí)吧。2016-11-11
使用Python實(shí)現(xiàn)獲取本機(jī)當(dāng)前用戶登陸過的微信ID
這篇文章主要為大家詳細(xì)介紹了如何使用Python實(shí)現(xiàn)獲取本機(jī)當(dāng)前用戶登陸過的微信對(duì)應(yīng)的wxid,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解下2025-07-07
Python中os.path.join函數(shù)的用法舉例詳細(xì)講解
這篇文章主要介紹了Python中os.path.join函數(shù)用法的相關(guān)資料,os.path.join函數(shù)用于拼接路徑,根據(jù)操作系統(tǒng)自動(dòng)選擇分隔符,它可以處理不同參數(shù)的情況,包括絕對(duì)路徑、空字符串和以特定字符開始的參數(shù),需要的朋友可以參考下2025-02-02
pycharm遠(yuǎn)程調(diào)試openstack的圖文教程
這篇文章主要為大家詳細(xì)介紹了pycharm遠(yuǎn)程調(diào)試openstack的圖文教程,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-11-11
利用Python實(shí)現(xiàn)批量轉(zhuǎn)換圖片格式
本文重點(diǎn)介紹普通圖片格式怎么相互轉(zhuǎn)換,如jpg格式圖片怎么批量轉(zhuǎn)化為png格式,在深度學(xué)習(xí)項(xiàng)目中,有時(shí)我們收集到的數(shù)據(jù)集圖片格式不統(tǒng)一,有的代碼支持多種格式圖片輸入,有的則只支持個(gè)別格式,所以這時(shí),我們需要通過腳本來轉(zhuǎn)換圖片格式,不說廢話,直接上代碼2025-08-08

