簡體   English   中英

如何使用python將本地文件推送到github? (或通過 Python 發布提交)

[英]How to push local files to github using python? (or post a commit via Python)

有哪些選項可以從 python 提交和推送文件到 github?

以下是我認為應該可行的三種方法,因此按順序嘗試:

  1. 使用pygithub : (Github 的 python API) 將推送請求發送到我的存儲庫。 失敗,因為我在 API 中找不到推送功能。 我可以看到編輯文件,但是當我計划經常替換文件時,這無濟於事。

  2. 在 python 子進程 (HTTPS) 的命令行中使用git push這幾乎有效,但我不知道如何填寫所需的用戶和密碼字段。 試圖:

     import subprocess from pexpect import popen_spawn user = 'GithubUsername' password = '***********' cmd = "cd C:\\\\Users\\Dropbox\\git-test" returned_value = subprocess.call(cmd, shell=True) # returns the exit code in unix cmd = "git add ." subprocess.call(cmd, shell=True) cmd = 'git commit -m "python project update"' subprocess.call(cmd, shell=True) cmd = "git remote set-url origin https://github.com/Tehsurfer/git-test.git" subprocess.call(cmd, shell=True) cmd = "git push " child_process = popen_spawn.PopenSpawn(cmd) child_process.expect('User') child_process.sendline(user) child_process.expect('Password') child_process.sendline(password) print('returned value:', returned_value) print('end of commands')`
  3. 在 python 子進程 (SSH) 的命令行中使用git push我在這里遇到的問題是我找不到在 Windows 命令提示符下創建 ssh 代理的方法。 通過本教程,我已經能夠在 MINGW64 終端中輕松創建一個,但無法通過 Python 與它進行交互。

如何將新文件推送到 GitHub?

一個非常相似的問題,我能夠修改誰的代碼以通過 python 將多個文件推送到 github:

import base64
from github import Github
from github import InputGitTreeElement

user = "GithubUsername"
password = "*********"
g = Github(user,password)
repo = g.get_user().get_repo('git-test') # repo name
file_list = [
    'C:\\Users\jesse\Dropbox\Swell-Forecast\git-test\index.html',
    'C:\\Users\jesse\Dropbox\Swell-Forecast\git-test\margin_table.html'
]
file_names = [
    'index.html',
    'margin_table.html'
]
commit_message = 'python commit'
master_ref = repo.get_git_ref('heads/master')
master_sha = master_ref.object.sha
base_tree = repo.get_git_tree(master_sha)

element_list = list()
for i, entry in enumerate(file_list):
    with open(entry) as input_file:
        data = input_file.read()
    if entry.endswith('.png'): # images must be encoded
        data = base64.b64encode(data)
    element = InputGitTreeElement(file_names[i], '100644', 'blob', data)
    element_list.append(element)

tree = repo.create_git_tree(element_list, base_tree)
parent = repo.get_git_commit(master_sha)
commit = repo.create_git_commit(commit_message, tree, [parent])
master_ref.edit(commit.sha)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM