溫馨提示×

python如何調用git命令

小億
125
2024-12-05 07:51:26
欄目: 編程語言

要在Python中調用Git命令,您可以使用subprocess模塊

import subprocess

# 獲取當前目錄下的所有Git倉庫
def get_git_repos(path):
    return [d for d in os.listdir(path) if os.path.isdir(os.path.join(path, d)) and os.path.exists(os.path.join(d, '.git'))]

# 調用Git命令并捕獲輸出
def run_git_command(repo_path, command):
    result = subprocess.run(['git', '-C', repo_path] + command, capture_output=True, text=True)
    return result.stdout, result.stderr

# 示例:獲取當前目錄下的所有Git倉庫
repos = get_git_repos('.')
print("Git repositories found:")
for repo in repos:
    print(repo)

# 示例:在第一個找到的Git倉庫中運行`git status`命令
if repos:
    stdout, stderr = run_git_command(repos[0], ['status'])
    print("\nOutput of 'git status' in the first repository:")
    print(stdout)
    if stderr:
        print("Error:")
        print(stderr)
else:
    print("No Git repositories found.")

這個示例中,get_git_repos函數用于獲取當前目錄下的所有Git倉庫,而run_git_command函數用于在指定的Git倉庫中運行Git命令。請注意,您需要將示例中的.替換為您要檢查的目錄路徑。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女