Skip to main content
 首页 » 编程设计

没有本地工作目录的 Github 远程仓库上的 Python 更新文件

2025年04月02日8myhome

这是关于在没有本地工作目录的情况下推送到远程仓库的问题 ( Python push files to Github remote repo without local working directory ) 的后续问题。我想知道如果该文件已经存在于远程仓库中,而我只想用修改后的同名文件更新它怎么办? (例如,相当于在Github网站上,上传远程已经存在的文件的修改版本)

编辑:我们想出了一个解决方案:

contents_object = repository.contents(file_path) 
push_status = contents_object.update("test_message",contents) 

然而,虽然这在一台机器上成功运行,但它在另一台机器上抛出错误(具体来说,第一行将得到一个 AttributeError)。这是因为 github3 的版本可能不同吗?

请您参考如下方法:

很明显,在 github3 版本 0.9.6 下,这是你将通过 pip install github3.py( https://github3py.readthedocs.io/en/master/#installation ) 获得的版本,这将起作用(进行更新到没有任何本地工作目录的远程仓库):

def update_to_git(username,password,path,account,repo,message): 
    files_to_upload = [path] 
    gh = github3.login(username=username, password=password) 
    repository = gh.repository(account, repo) 
    for file_info in files_to_upload: 
        with open(file_info, 'rb') as fd: 
            contents = fd.read() 
        contents_object = repository.contents(file_info) 
        contents_object.update(message,contents) 

但是,如果你有 github3 版本 1.0.0a4,这将不起作用。具体来说,您将获得 contents_object = repository.contents(file_info) 行的 AttributeError,这可能是由于 github3 中的实现发生了变化。