Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/git/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将新文件推送到GitHub?_Python_Git_Github_Pygithub - Fatal编程技术网

Python 如何将新文件推送到GitHub?

Python 如何将新文件推送到GitHub?,python,git,github,pygithub,Python,Git,Github,Pygithub,我在github.com上创建了一个新的存储库,然后用 git clone https://github.com/usrname/mathematics.git 我在文件夹mathematics $ tree . ├── LICENSE ├── numerical_analysis │   └── regression_analysis │   ├── simple_regression_analysis.md │   ├── simple_regression_analys

我在github.com上创建了一个新的存储库,然后用

git clone https://github.com/usrname/mathematics.git
我在文件夹
mathematics

$ tree 
.
├── LICENSE
├── numerical_analysis
│   └── regression_analysis
│       ├── simple_regression_analysis.md
│       ├── simple_regression_analysis.png
│       └── simple_regression_analysis.py
现在,我想使用Python将3个新文件上传到我的GitHub,更具体地说。以下是我尝试过的:

#!/usr/bin/env python
# *-* coding: utf-8 *-*
from github import Github

def main():
    # Step 1: Create a Github instance:
    g = Github("usrname", "passwd")
    repo = g.get_user().get_repo('mathematics')

    # Step 2: Prepare files to upload to GitHub
    files = ['mathematics/numerical_analysis/regression_analysis/simple_regression_analysis.py', 'mathematics/numerical_analysis/regression_analysis/simple_regression_analysis.png']

    # Step 3: Make a commit and push
    commit_message = 'Add simple regression analysis'

    tree = repo.get_git_tree(sha)
    repo.create_git_commit(commit_message, tree, [])
    repo.push()

if __name__ == '__main__':
    main()
我不知道

  • 如何获取
    repo.get\u git\u树的字符串
    sha
  • 如何在步骤2和步骤3之间建立连接,即推送特定文件
就个人而言,这是不可读的。在搜索了很长时间后,我无法找到正确的api

import subprocess
p = subprocess.Popen("git rev-parse HEAD".split(), stdout=subprocess.PIPE)
out, err = p.communicate()
sha = out.strip()

也许有一种方法可以通过PyGithub实现这一点,但这对于快速破解来说应该是有效的。

如果您不需要PyGithub,则dulwich git库提供。对于命令,请看一下

,我可以为您提供一些信息支持,但也可以提供一个具体的解决方案

您可以找到向存储库添加新文件的示例,这是一个视频教程

下面,您可以在GitHub的开发者页面上看到使用GitHub的python包列表:

但如果需要,也可以使用IPython中的命令推送文件:

In [1]: import subprocess
In [2]: print subprocess.check_output('git init', shell=True)
Initialized empty Git repository in /home/code/.git/
In [3]: print subprocess.check_output('git add .', shell=True)
In [4]: print subprocess.check_output('git commit -m "a commit"', shell=True)
我尝试使用提交多个文件。这一页的主题是“非常简单”。有关该调查的结果,请参阅

我建议您使用以下方法:


注意:此版本的脚本是在存储库的父目录中运行的。

如果PyGithub的文档不可用(而且看起来不可用),并且您只想推送提交(不要对问题、repo配置等做任何花哨的事情),那么直接与git交互可能会更好,调用
git
可执行文件或使用包装库,如

直接将
git
与您提到的
subprocess.Popen
这样的东西一起使用可能在学习曲线上更容易,但从长远来看,错误处理等方面也更难。因为您实际上没有很好的抽象来传递,并且必须自己进行解析


摆脱PyGithub还可以使您摆脱与GitHub及其API的绑定,从而可以推送到任何repo,甚至是计算机上的另一个文件夹。

注意:此版本的脚本是从GIT存储库内部调用的,因为我从文件路径中删除了存储库名称

我终于想出了如何使用提交多个文件:

import base64
from github import Github
from github import InputGitTreeElement

token = '5bf1fd927dfb8679496a2e6cf00cbe50c1c87145'
g = Github(token)
repo = g.get_user().get_repo('mathematics')
file_list = [
    'numerical_analysis/regression_analysis/simple_regression_analysis.png',
    'numerical_analysis/regression_analysis/simple_regression_analysis.py'
]
commit_message = 'Add simple regression analysis'
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 entry in file_list:
    with open(entry, 'rb') as input_file:
        data = input_file.read()
    if entry.endswith('.png'):
        data = base64.b64encode(data)
    element = InputGitTreeElement(entry, '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)
""" An egregious hack to change the PNG contents after the commit """
for entry in file_list:
    with open(entry, 'rb') as input_file:
        data = input_file.read()
    if entry.endswith('.png'):
        old_file = repo.get_contents(entry)
        commit = repo.update_file('/' + entry, 'Update PNG content', data, old_file.sha)
如果我尝试添加PNG文件中的原始数据,对
create\u git\u tree
的调用最终会调用
json.dumps
in,这导致引发以下异常:

UnicodeDecodeError:'utf8'编解码器无法解码位置0中的字节0x89:无效的开始字节


我通过
base64
编码PNG数据并提交来解决这个问题。稍后,我使用
update_file
方法更改PNG数据。这将导致对存储库的两个单独的提交,这可能不是您想要的。

使用子流程,这将完成相同的工作-

import subprocess
subprocess.call(['git', 'add', '-A'])
subprocess.call(['git', 'commit', '-m', '{}'.format(commit_message)])
subprocess.call(['git', 'push', 'https://{}@github.com/user-name/repo.git'.format(token)])

确保使用-A或-all跟踪项目/甚至父目录中的所有文件。使用“git add.”将只跟踪cwd中写入此代码的文件。

要获取
sha
您需要使用
hashlib
@WayneWerner,这绝对不是他应该做的。
sha
是由
git
计算的,如果你自己尝试计算,几乎肯定会出错。我可以知道否决票的原因吗?那么,直接调用
git
与之交互如何?或者使用python接口,例如,不一定是面向GitHub的?它的文件确实是。。。我对文档的理解是,您希望得到分支,从中可以得到头提交(从中可以得到提交的
sha
值和基树)。有了它,调用
create_git_tree
将头部的树作为基础传递给它,并给它一个
InputGitTreeElement
(设置
content
,但保留
sha
)的列表,进行修改。然后用新树调用
create\u git\u commit
。最后,您需要获取branch ref并将其更新到新的commit
sha
。找到一个封装这个的库可能比自己做要容易得多。Thx可以快速响应。如果您能提供MWE,那将非常好。@sparkandshine抱歉-什么是MWE?最简单的工作示例?没错,我以为我在一个旧项目中使用了dulwich,但实际上我只是通过那里的子进程使用普通的git命令-对不起,没有工作示例您只能在当前工作目录的根目录或子目录中添加文件,而不能从父目录添加文件。好吧,您只需执行
os.chdir()
处理其他目录或Git repo,例如使用单独的存储库进行备份时。上述内容也将继续在“新”git项目中使用。需要在文件列表中添加哪个路径?当我给出本地可用图像的路径时,会显示错误filenotfounderror winerror 2 python
import subprocess
subprocess.call(['git', 'add', '-A'])
subprocess.call(['git', 'commit', '-m', '{}'.format(commit_message)])
subprocess.call(['git', 'push', 'https://{}@github.com/user-name/repo.git'.format(token)])