import subprocess def get_uncommitted_changes(): """获取所有未提交的修改,并区分新增、删除、修改状态""" changes = { 'added': [], 'deleted': [], 'modified': [] } try: # 获取工作区和暂存区的完整状态 status_output = subprocess.check_output( ["git", "status", "--porcelain"], text=True, stderr=subprocess.DEVNULL ).splitlines() for line in status_output: status_code = line[:2].strip() file_path = line[3:].strip() if status_code == '??': changes['added'].append(file_path) elif status_code == 'D': changes['deleted'].append(file_path) elif status_code in ('M', 'AM', 'MD'): changes['modified'].append(file_path) except subprocess.CalledProcessError: pass return changes # 使用示例 changes = get_uncommitted_changes() for status, files in changes.items(): if files: print(f"\n{status.upper()}:") for file in files: print(f" - {file}")