如何通过Python推送本地文件至GitHub?可行方案及问题咨询
Alright, let's break down how to solve your problem. You've already discovered that PyGitHub doesn't support direct pushes (it only allows file edits via the API), which isn't practical for frequent file replacements. So let's focus on getting the subprocess + git push approach working properly—specifically handling authentication.
Option 1: HTTPS Authentication with a Personal Access Token (PAT)
This is the most straightforward method for automated pushes. You'll need a GitHub PAT (instead of your password, since password-based auth is deprecated for GitHub).
Step 1: Generate a GitHub PAT
Go to your GitHub Settings → Developer settings → Personal access tokens → Generate new token. Make sure to check the repo scope to give it permission to push to your repositories.
Step 2: Embed the PAT in the Remote URL (No Manual Input Needed)
You can inject the PAT into the remote URL (but never commit this to version control—use environment variables for security):
import subprocess import os repo_path = "/path/to/your/local/git/repo" github_username = "your-username" # Fetch PAT from environment variable to avoid hardcoding github_pat = os.getenv("GITHUB_PAT") # Update the remote origin URL to include your credentials remote_url = f"https://{github_username}:{github_pat}@github.com/{github_username}/your-repo-name.git" subprocess.run(["git", "remote", "set-url", "origin", remote_url], cwd=repo_path, check=True) # Perform git add, commit, push subprocess.run(["git", "add", "."], cwd=repo_path, check=True) subprocess.run(["git", "commit", "-m", "Automated file update via Python"], cwd=repo_path, check=True) subprocess.run(["git", "push", "origin", "main"], cwd=repo_path, check=True)
Step 3: Alternative: Use Git Credential Helper
If you don't want to embed credentials in the URL, use Git's credential helper to store your PAT so you only enter it once:
import subprocess repo_path = "/path/to/your/local/git/repo" # Set up credential helper to store credentials (run this once) subprocess.run(["git", "config", "--global", "credential.helper", "store"], check=True) # Now run your git commands—first time you'll be prompted for username and PAT, then it's saved subprocess.run(["git", "add", "."], cwd=repo_path, check=True) subprocess.run(["git", "commit", "-m", "Automated file update via Python"], cwd=repo_path, check=True) subprocess.run(["git", "push", "origin", "main"], cwd=repo_path, check=True)
Option 2: SSH Authentication (More Secure for Automation)
SSH keys eliminate the need to enter credentials entirely once set up, making this ideal for long-term automation.
Step 1: Set Up SSH Key for GitHub
- Generate an SSH key pair using
ssh-keygen(available in Git Bash, macOS Terminal, or Linux). - Add the public key to your GitHub account (Settings → SSH and GPG keys → New SSH key).
Step 2: Update Remote URL and Push via Python
import subprocess repo_path = "/path/to/your/local/git/repo" # Set remote origin to SSH URL remote_url = "git@github.com:your-username/your-repo-name.git" subprocess.run(["git", "remote", "set-url", "origin", remote_url], cwd=repo_path, check=True) # Run git commands subprocess.run(["git", "add", "."], cwd=repo_path, check=True) subprocess.run(["git", "commit", "-m", "Automated file update via Python"], cwd=repo_path, check=True) subprocess.run(["git", "push", "origin", "main"], cwd=repo_path, check=True)
Key Notes
- Security: Never hardcode your PAT or password in your Python script. Use environment variables or secure vaults instead.
- Error Handling: Add
try-exceptblocks aroundsubprocess.run()to catch git errors (like merge conflicts or authentication failures). - Branch Names: Replace
mainwith your target branch name if it's different (e.g.,master).
内容的提问来源于stack exchange,提问作者Jesse Reza Khorasanee

