如何在使用gitpython时设置git用户名和密码?

6 投票
1 回答
3100 浏览
提问于 2025-04-18 15:51

我打算在我的项目中使用GitPython。当我测试时,运行这段代码时出现了一个错误。

repo.index.add(['*']) 
repo.index.commit(message="Initial Commit")
repo.remotes.origin.push()

错误信息是:

Traceback (most recent call last):
  File "test.py", line 24, in <module>
    repo.remotes.origin.push()
  File "C:\Python27\lib\site-packages\git\remote.py", line 627, in push
    return self._get_push_info(proc, progress or RemoteProgress())
  File "C:\Python27\lib\site-packages\git\remote.py", line 564, in _get_push_info
    finalize_process(proc)
  File "C:\Python27\lib\site-packages\git\remote.py", line 64, in finalize_process
    proc.wait()
  File "C:\Python27\lib\site-packages\git\cmd.py", line 100, in wait
    raise GitCommandError(self.args, status, self.proc.stderr.read())
git.exc.GitCommandError: 'git push --porcelain origin' returned exit status 128:

最后一行之后没有任何信息。不过,如果我在命令行手动运行 git push --porcelain origin,我会收到这个错误:

fatal: could not read Username for 'https://github.com': No such file or directory

这个错误是合理的。因为这是一个全新的代码库,我还没有完全配置好。不过,我计划在多个机器上部署这个项目(以及推送的功能),所以我希望能通过GitPython自动完成这件事。

我该如何设置用户名和密码(或者使用SSH密钥)来推送到远程代码库呢?

1 个回答

0

你需要手动推送一次,也就是用命令 git push -u origin <branch_name>,这样你的本地仓库才能在远程服务器上被识别。第一次这样做之后,你就不会再遇到这个问题了。

撰写回答