SoFunction
Updated on 2025-03-04

Project Practice for Python Operation Git

Hello everyone, when it comes to version control systems, Git is the most widely used one, and Python, as a multi-purpose programming language, also demonstrates its powerful capabilities when dealing with Git repositories. With Python, we can easily interact with the Git repository and perform various operations, from simple commit files to repositories to complex branch management and history queries. In this article, we will explore how to use Python to operate Git. With the help of the GitPython library, we can complete this task more easily.

In the following content, we will introduce how to use Python and GitPython libraries for various operations in Git repository. First, we will learn how to install the GitPython library and import the required modules. We will then learn how to open a Git repository, query the state of the repository, add and commit changes, create and switch branches, view commit history, and interact with remote repository.

1. Install GitPython

First, installation is requiredGitPythonlibrary. You can use the pip command to install:

pip install gitpython

2. Use GitPython

1. Open the Git repository

To useGitPython, first you need to open a Git repository. Here is a simple example:

import git

# Specify the path to the local repositoryrepo_path = '/path/to/your/repository'

# Open the warehouserepo = (repo_path)

2. Query the warehouse status

Query the status of the warehouse, that is, check which files in the working directory have been modified, deleted or added:

# Get the status of the warehouserepo_status = ()
print(repo_status)

3. Add files to the temporary storage area

Add all modified files in the working directory to the temporary storage area:

# Add all files to the temporary storage area(all=True)

4. Submit changes

Submit changes in the staging area to the repository:

# Submit changes('-m', 'Your commit message')

5. Check the submission history

Check the commit history of the warehouse:

# Get submission historycommit_history = list(repo.iter_commits())
for commit in commit_history:
    print(commit)

6. Create a new branch

Create a new branch:

# Create a new branchrepo.create_head('new_branch')

7. Switch branches

Switch to the specified branch:

# Switch to the specified branch('branch_name')

8. Pull remote updates

Pull updates from remote repository to local repository:

# Pull remote updates()

9. Push local changes to remote

Push changes from the local repository to the remote repository:

# Push local changes to remote()

10.Clone the remote repository

Use GitPython Coupon to clone the remote repository to the local area:

#Clone the remote repository to the local.clone_from('/username/', '/path/to/destination')

11. View remote warehouse information

View information about remote repository, such as URLs, branches, etc.:

# Obtain remote warehouse informationremote = ()
print("Remote URL:", )
print("Remote branches:", )

12. Check the current branch

Check the current branch:

# Get the current branchcurrent_branch = repo.active_branch
print("Current branch:", current_branch)

13. Create and switch to a new branch

Create a new branch and switch to that branch:

# Create and switch to a new branchnew_branch = repo.create_head('new_branch')
new_branch.checkout()

14. Revoke uncommitted changes

Undo all uncommitted changes in the working directory:

# Undo uncommitted changes('--hard', 'HEAD')

15. Delete the branch

Delete the specified branch:

# Delete the branchrepo.delete_head('branch_name')

16. Obtain the current working directory

Get the path to the current working directory:

# Get the current working directory pathworking_dir = repo.working_dir
print("Working directory:", working_dir)

17. Get Git configuration information

Get the configuration information of the Git repository:

# Get Git configuration informationconfig_info = ('--list')
print("Git configuration:", config_info)

18. View file history

View the historical submission history of the specified file:

# Specify file pathfile_path = 'path/to/'

# Get the historical submission record of the filefile_history = ('--follow', '--', file_path)
print("File history:", file_history)

19. Check file status

Check the status of the specified file, including whether it has been modified, whether it is a new file, etc.

# Get the status of the specified filefile_status = (file_path)
print("File status:", file_status)

20. Check whether there are any uncommitted changes

Check for uncommitted changes in the working directory:

# Check for uncommitted changeshas_changes = repo.is_dirty()
print("Has changes:", has_changes)

21. Obtain the submitted author information

Get the most recently submitted author information:

# Get the most recently submitted author informationlatest_commit = 
author = latest_commit.author
print("Latest commit author:", author)

22. View the submitted changes

View the most recently submitted changes:

# View the most recently submitted changeslatest_commit_diff = latest_commit.diff()
print("Latest commit diff:", latest_commit_diff)

23. Obtain the specified submission of changes

Get the changes to the specified submission:

# Get the specified submission of changesspecified_commit = ('commit_sha')
specified_commit_diff = specified_commit.diff()
print("Specified commit diff:", specified_commit_diff)

24. View file differences

Compare the differences in files between the two versions:

# Specify two versions of commit objectscommit_1 = ('commit_sha_1')
commit_2 = ('commit_sha_2')

# Compare the differences in files between two versionsdiff = commit_1.diff(commit_2)
print("File diff between commit 1 and commit 2:", diff)

25. View the contents of the specified file

View the content of the specified file in a commit:

# Specify the file path and the committed commit objectfile_path = 'path/to/'
commit = ('commit_sha')

# View the content of the specified file in a commitfile_content = [file_path].data_stream.read().decode("utf-8")
print("Content of file in specified commit:", file_content)

26. Roll back to the specified version

Roll back the repository to the specified version:

# Specify the commit object to rollback tocommit_to_rollback = ('commit_sha')

# Roll back to the specified version('--hard', commit_to_rollback)

27. Get the branch list

# Get the branch listbranch_list = ('-a').split('\n')
print("Branch list:", branch_list)

28. Get the tag list

Get a list of all tags:

# Get the tag listtag_list = ().split('\n')
print("Tag list:", tag_list)

3. Complete example

Here is a very complete example that demonstrates how to use itGitPythonThe library performs a series of Git operations, including initializing the repository, adding files, committing changes, creating branches, switching branches, viewing commit history, pulling remote updates, pushing local changes, etc.

import git

# 1. Initialize the warehouserepo = ('/path/to/your/repository')

# 2. Create a new file and add it to the staging areafile_path = '/path/to/your/repository/new_file.txt'
with open(file_path, 'w') as f:
    ("Hello, GitPython!")
(file_path)

# 3. Submit changes('-m', 'Add a new file')

# 4. Create and switch to a new branchnew_branch = repo.create_head('new_branch')
new_branch.checkout()

# 5. Modify the file and commit the changes in the new branchwith open(file_path, 'a') as f:
    ("\nNew line added in new branch")
(file_path)
('-m', 'Modify file in new branch')

# 6. Switch back to the main branch('master')

# 7. View submission historycommit_history = list(repo.iter_commits())
print("Commit history:")
for commit in commit_history:
    print(commit)

# 8. Pull remote updates()

# 9. Push local changes to remote repository()

This is the end of this article about the project practice of Python operating Git. For more related content on Python operating Git, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!