SoFunction
Updated on 2025-03-02

Python sample code to get the current git repo address

To get the remote address of the current Git repository, you can usesubprocessThe module executes the Git command. Here is a sample code for how to do this:

import subprocess

def get_git_remote_url():
    try:
        # Get the remote URL        result = (
            ['git', 'config', '--get', ''],
            check=True,
            stdout=,
            stderr=,
            text=True
        )
        
        # Get and return output        remote_url = ()
        return remote_url

    except  as e:
        print(f"An error occurred: {e}")
        return None

#User Exampleremote_url = get_git_remote_url()
if remote_url:
    print(f"Remote URL: {remote_url}")
else:
    print("Failed to retrieve the remote URL.")

Notes:

  • Git must be installed: Make sure that Git is installed in the local environment and is running in the directory of the Git repository.
  • Error handling: The code simply handles possible errors and can add exception handling and logging as needed.
  • Remote name: The example uses the defaultorigin, If the remote name is different, please change the corresponding part in the command.

Expand: Python operates git gitpython module

Install the module

pip3 install gitpython

Basic use

import os
from  import Repo

# Create a local path to store the code downloaded from the remote repositorydownload_path = ('NB')
# Pull the codeRepo.clone_from('/DominicJi/',to_path=download_path,branch='master')

Other common operations

# #################### 2. Pull the latest code ##################import os
from  import Repo
 
local_path = ('NB')
repo = Repo(local_path)
()


# ###################### 3. Get all branches ##################import os
from  import Repo
 
local_path = ('NB')
repo = Repo(local_path)
 
branches = ().refs
for item in branches:
    print(item.remote_head)
    

# ####################### 4. Get all versions #################import os
from  import Repo
 
local_path = ('NB')
repo = Repo(local_path)
 
for tag in :
    print()


# ###################### 5. Get all commit ##################import os
from  import Repo
 
local_path = ('NB')
repo = Repo(local_path)
 
# Format all submission records into json format strings to facilitate subsequent deserialization operationscommit_log = ('--pretty={"commit":"%h","author":"%an","summary":"%s","date":"%cd"}', max_count=50,
                          date='format:%Y-%m-%d %H:%M')
log_list = commit_log.split("\n")
real_log_list = [eval(item) for item in log_list]
print(real_log_list)
 

 # ##################### 6. Switch branch ###################import os
from  import Repo
 
local_path = ('NB')
repo = Repo(local_path)
 
before = ()
print(before)
('master')
after = ()
print(after)
('--hard', '854ead2e82dc73b634cbd5afcf1414f5b30e94a8')


 
# ##################### 7. Packaging code ##################import os
from  import Repo

local_path = (NB')
repo = Repo(local_path)

with open((''), 'wb') as fp:
    (fp)

All methods are encapsulated into the class

import os
from  import Repo
from  import is_git_dir


class GitRepository(object):
    """
     git warehouse management
     """
    def __init__(self, local_path, repo_url, branch='master'):
        self.local_path = local_path
        self.repo_url = repo_url
         = None
        (repo_url, branch)

    def initial(self, repo_url, branch):
        """
         Initialize the git repository
         :param repo_url:
         :param branch:
         :return:
         """
        if not (self.local_path):
            (self.local_path)

        git_local_path = (self.local_path, '.git')
        if not is_git_dir(git_local_path):
             = Repo.clone_from(repo_url, to_path=self.local_path, branch=branch)
        else:
             = Repo(self.local_path)

    def pull(self):
        """
         Pull the latest code from online
         :return:
         """
        ()

    def branches(self):
        """
         Get all branches
         :return:
         """
        branches = ().refs
        return [item.remote_head for item in branches if item.remote_head not in ['HEAD', ]]

    def commits(self):
        """
         Get all submission records
         :return:
         """
        commit_log = ('--pretty={"commit":"%h","author":"%an","summary":"%s","date":"%cd"}',
                                       max_count=50,
                                       date='format:%Y-%m-%d %H:%M')
        log_list = commit_log.split("\n")
        return [eval(item) for item in log_list]

    def tags(self):
        """
         Get all tags
         :return:
         """
        return [ for tag in ]

    def change_to_branch(self, branch):
        """
         Switch scores
         :param branch:
         :return:
         """
        (branch)

    def change_to_commit(self, branch, commit):
        """
         Switch commit
         :param branch:
         :param commit:
         :return:
         """
        self.change_to_branch(branch=branch)
        ('--hard', commit)

    def change_to_tag(self, tag):
        """
         Switch tag
         :param tag:
         :return:
         """
        (tag)


if __name__ == '__main__':
    local_path = ('codes', 'luffycity')
    repo = GitRepository(local_path,remote_path)
    branch_list = ()
    print(branch_list)
    repo.change_to_branch('dev')
    ()

This is the article about python's sample code to obtain the current git repo address. For more related python's content to obtain the git repo address, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!