pip如何通过git来安装包

pip 支持通过 git 安装 Python 包,通常用于安装托管在 Git 仓库中的自定义包或者未发布到 PyPI 的包。以下是通过 git 安装 Python 包的几种方法和技巧。


1. 基本语法

通过 git 安装包的基本命令格式如下:

pip install git+<repository_url>
例子

安装托管在 GitHub 上的一个包:

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

2. 指定分支

如果仓库有多个分支,可以通过 @branch_name 指定要安装的分支:

pip install git+https://github.com/username/repository.git@branch_name
例子

安装仓库中 develop 分支的代码:

pip install git+https://github.com/username/repository.git@develop

3. 指定提交哈希(commit hash)

如果需要安装特定版本的代码,可以通过 @commit_hash 指定提交哈希:

pip install git+https://github.com/username/repository.git@commit_hash
例子

安装某个特定提交(例如,abc123):

pip install git+https://github.com/username/repository.git@abc123

4. 指定标签(Tag)

通过 Git 标签安装特定版本的包:

pip install git+https://github.com/username/repository.git@tag_name
例子

安装某个版本的包(例如,v1.0.0):

pip install git+https://github.com/username/repository.git@v1.0.0

5. 包含子目录的包

如果包代码不在仓库根目录下,而在子目录中,可以通过 #subdirectory 指定子目录路径:

pip install git+https://github.com/username/repository.git@branch_name#subdirectory=path/to/subdirectory
例子

仓库结构如下:

repository/
├── submodule/
│   ├── setup.py

安装 submodule 子目录中的包:

pip install git+https://github.com/username/repository.git@main#subdirectory=submodule

6. 使用 SSH 安装

如果仓库是私有的,且你有 SSH 访问权限,可以通过 SSH 克隆并安装:

pip install git+ssh://git@github.com/username/repository.git
例子
pip install git+ssh://git@github.com/username/repository.git@main

7. 安装到本地(开发模式)

如果你希望以开发模式安装包,可以加上 -e 参数(editable mode)。这适用于本地仓库或远程仓库:

pip install -e git+<repository_url>
例子
pip install -e git+https://github.com/username/repository.git@develop

8. 指定 requirements.txt 文件中的 Git 包

requirements.txt 中,也可以指定通过 git 安装的包:

git+https://github.com/username/repository.git@main
git+https://github.com/username/repository.git@v1.0.0#subdirectory=path/to/submodule

然后用以下命令安装:

pip install -r requirements.txt

9. 使用访问令牌(私有仓库)

如果要安装私有仓库中的包,且没有使用 SSH,可以使用 GitHub 的访问令牌(Personal Access Token, PAT):

pip install git+https://<token>@github.com/username/repository.git
例子

假设访问令牌是 ghp_ABC1234567890

pip install git+https://ghp_ABC1234567890@github.com/username/repository.git

10. 注意事项

  1. 安装带有依赖的包: 确保仓库中的 setup.pypyproject.toml 文件已正确配置依赖项。
  2. 版本控制: 如果没有指定分支、标签或提交哈希,pip 默认会安装仓库的 HEAD
  3. 私有仓库访问: 使用 SSH 或访问令牌时,请注意敏感信息的安全性。

通过这些方法,你可以轻松通过 git 安装托管在远程或本地的 Python 包。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

rock——you

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值