Git通过GitPython推送

ami*_*igo 6 python git push gitpython

我在Python中使用此代码(使用"import git"):

repo = git.Repo("my_repository")
repo.git.add("bla.txt")
repo.git.commit("my commit description")
Run Code Online (Sandbox Code Playgroud)

现在我想推动这个提交.我已经尝试了很多但没有成功.Python命令应该与此Bash命令类似:

git push origin HEAD:refs/for/master
Run Code Online (Sandbox Code Playgroud)

Bla*_*ard 20

以下是git addgit commit然后git push使用 GitPython的代码。

安装GitPython使用pip install gitpython

from git import Repo

PATH_OF_GIT_REPO = r'path\to\your\project\folder\.git'  # make sure .git folder is properly configured
COMMIT_MESSAGE = 'comment from python script'

def git_push():
    try:
        repo = Repo(PATH_OF_GIT_REPO)
        repo.git.add(update=True)
        repo.index.commit(COMMIT_MESSAGE)
        origin = repo.remote(name='origin')
        origin.push()
    except:
        print('Some error occured while pushing the code')    

git_push()
Run Code Online (Sandbox Code Playgroud)

  • @nerdguy 提示:在 git ssh 上进行一些搜索。将使生活变得更加轻松和安全。无需使用密码和 http :) (3认同)

Sha*_*aji 5

您可以尝试以下操作。或许可以解决你的问题...

repo.git.pull('origin', new_branch)
repo.git.push('origin', new_branch)
Run Code Online (Sandbox Code Playgroud)


Kab*_*ard 1

查看gitpython http://gitpython.readthedocs.io/en/stable/tutorial.html的文档页面。你必须定义一个远程仓库,比如origin = repo.create_remote('origin', repo.remotes.origin.url)

然后origin.pull()

我会查看“处理遥控器”部分文档中的整个示例

这是文档中的完整示例

empty_repo = git.Repo.init(osp.join(rw_dir, 'empty'))
origin = empty_repo.create_remote('origin', repo.remotes.origin.url)
assert origin.exists()
assert origin == empty_repo.remotes.origin == empty_repo.remotes['origin']
origin.fetch()                  # assure we actually have data. fetch() returns useful information
# Setup a local tracking branch of a remote branch
empty_repo.create_head('master', origin.refs.master)  # create local branch "master" from remote "master"
empty_repo.heads.master.set_tracking_branch(origin.refs.master)  # set local "master" to track remote "master
empty_repo.heads.master.checkout()  # checkout local "master" to working tree
# Three above commands in one:
empty_repo.create_head('master', origin.refs.master).set_tracking_branch(origin.refs.master).checkout()
# rename remotes
origin.rename('new_origin')
# push and pull behaves similarly to `git push|pull`
origin.pull()
origin.push()
# assert not empty_repo.delete_remote(origin).exists()     # create and delete remotes
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,我已经看过这个例子,但它仍然对我不起作用...第一行有一个错误 origin = repo.create_remote('origin', repo.remotes.origin.url): "git remote添加源 ssh:........ 返回退出状态 128: 致命: 远程源已存在。有什么建议吗? (2认同)