Reference - Poetry/Reference - Poetry(Chinese Version)
序言
在这篇文章中,我想介绍如何使用Conda以及Poetry管理项目环境。
我们使用Conda实现Ptyhon多版本的管理
使用Poetry实现Ptyhon项目的依赖包管理
Conda:环境(env)管理
- 安装Minconda
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh bash Miniconda3-latest-Linux-x86_64.sh
-
第一次安装时使用
source ~/.bashrc
激活base环境 -
使用
conda config --set auto_activate_base false
关闭base环境的自动激活 - 创建虚拟环境
conda create -n your_env_name python=3.9
- 激活虚拟环境
conda activate your_env_name
- 退出虚拟环境
conda deactivate your_env_name
- 删除环境(如果需要)
conda remove -n your_env_name --all
- 如果需要的话
- 在虚拟环境中使用
conda env export > environment.yml
导出虚拟环境 - 在base环境中使用
conda env export -n ENVNAME > environment.yml
导出虚拟环境 - 也可以用
conda env export --from-history > environment.yml
仅导出包,不导出依赖包
- 在虚拟环境中使用
- 使用
conda env create -f environment.yaml
重新生成环境
Poetry: 依赖(dependence)管理
- 安装Poetry
curl -sSL https://install.python-poetry.org | python3 -
- 将
export PATH="$HOME/.local/bin:$PATH"
加入.bashrcecho 'export PATH="$HOME/.local/bin:$PATH"'>> ~/.bashrc source ~/.bashrc
- 全局关闭poetry的创建虚拟环境,注意此时不要在conda环境中
poetry config virtualenvs.create false
- 关于Poetry的操作见Reference - Poetry(Chinese Version),这里只提及与conda的协作
pyporject.toml
-
这是poetry最重要的文件之一,一个基本的
pyproject.toml
如下所示# pyproject.toml [tool.poetry] name = "rp-poetry" version = "0.1.0" description = "" authors = ["Philipp <philipp@realpython.com>"] [tool.poetry.dependencies] python = "^3.9" [tool.poetry.dev-dependencies] pytest = "^5.2" [build-system] requires = ["poetry-core>=1.0.0"] build-backend = "poetry.core.masonry.api"
-
在激活了conda以后
- 在[tool.poetry.dependencies]添加需要的包 / 使用
poetry add <package name>
添加包 - 使用
poetry lock
锁定依赖 - 使用
poetry install
安装依赖 - 使用
poetry show
查看
此时所有的poetry依赖将都安装在当前conda环境内,对外部不会有影响
- 在[tool.poetry.dependencies]添加需要的包 / 使用
总结
使用Conda + Poetry的方式,可以根据Python的版本管理不同的依赖