使用 poetry 进行依赖管理
1、安装及使用
1)执行 pip install poetry
最好全局安装,不同项目之间切换时不用重复激活和安装依赖,比较方便。
2)如果是新项目,则可使用 poetry 初始化。执行 poetry new poetry-demo
,项目结构如下:
1 | poetry-demo |
3)如果是既有项目引入 poetry,可在项目根目录执行 poetry init
,通过互动配置生成 pyproject.toml
文件。
win 环境下,默认虚拟环境在
C:\Users\用户名\AppData\Local\pypoetry\Cache\virtualenvs
目录下,虚拟环境名称会包含项目名称。
2、常用命令
poetry shell
,进入虚拟环境
注意:poetry 2.0.0 后该命令变更为插件,需另外安装
poetry self add poetry-plugin-shell
。详见 issues#9962
根据 pyproject.toml
文件来确定需要启动的虚拟环境。
poetry install
,安装全部依赖。
例如从远程仓库 clone 的项目不包含依赖,执行该命令则按 poetry.lock
新建。
poetry install --no-dev
,安装非开发环境的依赖,部署时使用poetry add <name>
,引入依赖,会同时更新poetry.lock
文件
可指定为开发时依赖:
poetry add <name> --dev
,将添加到[tool.poetry.dev-dependencies]
区域
poetry lock
,更新poetry.lock
文件
如果手工修改了 pyproject.toml
,比如指定特定模块的版本,此时 poetry.lock
的内容与 pyproject.toml
出现了脱钩,应执行上述命令保持两者一致。注意:该命令仅更新文件,不会安装模块至虚拟环境,要再使用 poetry install
安装模块。
因此,在执行完 poetry lock 指令后,必须再使用 poetry install 来安装模块
poetry update
,更新依赖,或poetry update requests
指定更新某个依赖poetry show
,列出当前环境已安装依赖,或poetry show -t
以树形结构查看
显示的是
poetry.lock
的内容
poetry show --tree
,树状显示模块依赖层级,或poetry show requests --tree
仅显示指定模块的依赖层级poetry remove <name>
,移除依赖poetry config --list
,查看 poetry 配置poetry source show
,显示下载源poetry source remove <源名称>
,删除下载源``
3、实用设置
1)将虚拟环境建立在项目目录下。
- 使用
poetry config --list
指令查看当前配置,如下所示; - 执行
poetry config virtualenvs.in-project true
,修改配置,将虚拟环境建立在项目目录; - 执行
poetry env remove python
删除默认路径的虚拟环境; - 执行
poetry env use python
重建虚拟环境,名称为.venv
1 | Using version ^2.1.4 for pandas |
虚拟环境在项目目录时,注意添加
.venv
到.gitignore
2)增加下载源
使用默认源有时会出现连接超时的情况,可执行 poetry source add <source_name> <source_url>
添加任一国内源解决这个问题:
poetry source add aliyun https://mirrors.aliyun.com/pypi/simple/
,添加阿里源【首选】poetry source add tsinghua https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple/
,添加清华源poetry source add tencent https://mirrors.cloud.tencent.com/pypi/simple/
,添加腾讯源
4、其他
1)当添加自定义源后,可能会遇到如下警告:
1 | Warning: In a future version of Poetry, PyPI will be disabled automatically if at least one custom primary source is configured. In order to avoid a breaking change and make your pyproject.toml forward compatible, add PyPI explicitly via 'poetry source add pypi'. By the way, this has the advantage that you can set the priority of PyPI as with any other source. |
按照提示,执行 poetry source add pypi
即可。