git和python交互,如何使用python将本地文件推送到github? (或通过Python发布提交)...

What options are there for commiting and pushing files to github from python?

Here are three methods I thought should be feasible so attempted in order:

Use git push in command line from a python subprocess (HTTPS): This almost works, but I cannot figure out how to fill in the user and password fields required. Attempt:

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')`

Use git push in command line from a python subprocess (SSH): The problem I had here is that I cannot find a way to create a ssh agent in the windows command prompt. I have been able to create one in the MINGW64 terminal easily enough via this tutorial , but have no way of interacting with it via Python.

解决方案

A very similar question who's code I was able to modify to make multiple file pushes to github via python:

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')

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 update 2'

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'):

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值