How to Stage All Modified Files with git add -u in Python
Runs git add -u from Python to stage all modified and deleted tracked files, then prints the short status.
Python code
29 linesimport subprocess
def stage_all_modified_files(repo_path="."):
"""Run git add -u to stage all modified and deleted tracked files."""
result = subprocess.run(
["git", "add", "-u"],
cwd=repo_path,
capture_output=True,
text=True,
)
if result.returncode != 0:
print(f"Error staging files: {result.stderr.strip()}")
return False
# Show what's now staged
status = subprocess.run(
["git", "status", "--short"],
cwd=repo_path,
capture_output=True,
text=True,
)
print("Staged changes (M = modified, D = deleted):")
print(status.stdout)
return True
if __name__ == "__main__":
stage_all_modified_files()
Output
Staged changes (M = modified, D = deleted):
M file1.py
D old_file.txt
How it works
The subprocess.run call executes git add -u in the specified repo path. -u stands for 'update' and stages changes to files that Git already tracks, including modifications and deletions but not new untracked files. The capture_output and text arguments let you read the result as text, and the return code check surfaces errors like a missing Git repo. Running git status --short afterward prints a concise list of staged changes, prefixed with 'M' for modified and 'D' for deleted.
Common mistakes
- Forgetting to include -u, which would stage new untracked files too.
- Not checking the return code, so errors appear silently.
- Hardcoding the repo path instead of accepting it as a parameter.
- Using text=True before Python 3.7, where it wasn't supported.
Variations
- Use `git add -A` if you also want to stage new untracked files.
- Parse status output with `git status --porcelain` for easier scripting.
Real-world use cases
- Automating pre-commit staging in a CI script before running tests or linters.
- Building a custom Git helper tool that stages changes based on filters.
- Synchronizing a working directory with a remote by staging all changes programmatically.
Sponsored
More from Git + Python
- Amend Last Commit Message in Python easy
- Bisect Good Bad Automation Script in Python easy
- Build a Simple Log Graph in Python easy
- Bump Semantic Version Git Tag in Python easy
- Count Unique Contributors from Git Shortlog in Python easy
- Create a Mock GitHub Release API in Python for Testing gh CLI easy
Keep learning
Related tutorials and quizzes for this topic.