文章目录
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. 注意事项
- 安装带有依赖的包: 确保仓库中的
setup.py
或pyproject.toml
文件已正确配置依赖项。 - 版本控制: 如果没有指定分支、标签或提交哈希,
pip
默认会安装仓库的HEAD
。 - 私有仓库访问: 使用 SSH 或访问令牌时,请注意敏感信息的安全性。
通过这些方法,你可以轻松通过 git
安装托管在远程或本地的 Python 包。