How do I use a GitHub access token with GitPython?

  • Dec 29, 2023
  • 1
  • 1k

I am trying to write a python script that when run, will push files to one of my GitHub repositories. I'm using the package GitPython. I want to use an access token to log in into my GitHub account (instead of entering my username and password) because I have two-factor authentication.

Answers (1)

Make sure to replace 'https://github.com/your-username/your-repo.git' with the actual URL of your GitHub repository, 'file1.txt', 'file2.txt' with the list of files you want to push, 'Add new files' with your desired commit message, and 'your-personal-access-token' with your actual GitHub personal access token.

Remember to keep your access token secure and not share it with others. You can create a personal access token in your GitHub account settings under "Developer settings" -> "Personal access tokens." Make sure to grant the necessary permissions (e.g., repo) when creating the token.

from git import Repo
import os

def push_to_github(repo_path, file_paths, commit_message, access_token):
    # Clone the repository
    repo = Repo.clone_from(repo_path, 'temp_repo')

    try:
        # Add files to the index
        repo.index.add(file_paths)

        # Create a new commit
        repo.index.commit(commit_message)

        # Set up the GitHub credentials using the access token
        github_url = repo_path.replace('https://', f'https://{access_token}@')
        repo.git.remote('set-url', 'origin', github_url)

        # Push the changes to the GitHub repository
        repo.git.push('origin', 'master')

    finally:
        # Cleanup: Delete the temporary repository
        if os.path.exists('temp_repo'):
            os.system('rm -rf temp_repo')

# Example usage
repo_path = 'https://github.com/your-username/your-repo.git'
file_paths = ['file1.txt', 'file2.txt']
commit_message = 'Add new files'
access_token = 'your-personal-access-token'

push_to_github(repo_path, file_paths, commit_message, access_token)
Submit your answer