可以用pip从私人GitHub仓库安装包吗?

565 投票
17 回答
435798 浏览
提问于 2025-04-16 10:47

我正在尝试从一个私有的GitHub仓库安装一个Python包。对于公共仓库,我可以使用以下命令,这样可以正常工作:

pip install git+git://github.com/django/django.git

但是,如果我尝试对一个私有仓库使用这个命令:

pip install git+git://github.com/echweb/echweb-utils.git

我得到的输出是:

Downloading/unpacking git+git://github.com/echweb/echweb-utils.git
Cloning Git repository git://github.com/echweb/echweb-utils.git to /var/folders/cB/cB85g9P7HM4jcPn7nrvWRU+++TI/-Tmp-/pip-VRsIoo-build
Complete output from command /usr/local/bin/git clone git://github.com/echweb/echweb-utils.git /var/folders/cB/cB85g9P7HM4jcPn7nrvWRU+++TI/-Tmp-/pip-VRsIoo-build:
fatal: The remote end hung up unexpectedly

Cloning into /var/folders/cB/cB85g9P7HM4jcPn7nrvWRU+++TI/-Tmp-/pip-VRsIoo-build...

----------------------------------------
Command /usr/local/bin/git clone git://github.com/echweb/echweb-utils.git /var/folders/cB/cB85g9P7HM4jcPn7nrvWRU+++TI/-Tmp-/pip-VRsIoo-build failed with error code 128

我猜这是因为我在没有提供任何身份验证的情况下尝试访问一个私有仓库。因此,我尝试使用Git和ssh,希望pip能使用我的SSH公钥进行身份验证:

pip install git+ssh://github.com/echweb/echweb-utils.git

这给出的输出是:

Downloading/unpacking git+ssh://github.com/echweb/echweb-utils.git
Cloning Git repository ssh://github.com/echweb/echweb-utils.git to /var/folders/cB/cB85g9P7HM4jcPn7nrvWRU+++TI/-Tmp-/pip-DQB8s4-build
Complete output from command /usr/local/bin/git clone ssh://github.com/echweb/echweb-utils.git /var/folders/cB/cB85g9P7HM4jcPn7nrvWRU+++TI/-Tmp-/pip-DQB8s4-build:
Cloning into /var/folders/cB/cB85g9P7HM4jcPn7nrvWRU+++TI/-Tmp-/pip-DQB8s4-build...

Permission denied (publickey).

fatal: The remote end hung up unexpectedly

----------------------------------------
Command /usr/local/bin/git clone ssh://github.com/echweb/echweb-utils.git /var/folders/cB/cB85g9P7HM4jcPn7nrvWRU+++TI/-Tmp-/pip-DQB8s4-build failed with error code 128

我想要实现的事情到底可不可以?如果可以的话,我该怎么做呢?

17 个回答

56

你可以直接使用HTTPS链接,像这样:

pip install git+https://github.com/username/repo.git

在一个Django项目中,你也可以把这一行直接加到requirements.txt文件里,这样也能用。

100

作为一种额外的技巧,如果你已经把私有仓库克隆到本地了,你可以这样做:

pip install git+file://c:/repo/directory

更现代的方法是,你可以直接这样做(这里的 -e 意思是你不需要在更改生效之前先提交这些更改):

pip install -e C:\repo\directory
611

你可以使用 git+ssh 这种格式的地址,但你 必须 设置一个用户名。注意地址中的 git@ 部分:

pip install git+ssh://git@github.com/echweb/echweb-utils.git

另外,可以看看关于 部署密钥 的内容。

附注:在我的安装中,"git+ssh" 这种格式的地址只在 "可编辑" 的需求下有效:

pip install -e URI#egg=EggName

记住:在使用远程地址的 pip 命令之前,要把 git remote -v 输出的 : 字符改成 / 字符:

$ git remote -v
origin  git@github.com:echweb/echweb-utils.git (fetch)
#                     ^ change this to a '/' character

如果你忘了这样做,就会出现这个错误:

ssh: Could not resolve hostname github.com:echweb:
         nodename nor servname provided, or not known

撰写回答