要在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命令。請注意,您需要將示例中的.
替換為您要檢查的目錄路徑。