Python包管理之poetry的使用

poetry介绍

poetry是一个Python虚拟环境和依赖管理的工具。poetrypipenv类似,另外还提供了打包和发布的功能。

跳转官方文档

poetry安装

方式一(curl)

curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python

方式二(pip)

pip install poetry

项目工程的初始化

poetry创建工程

poetry new zhenzi0322

提示Created package zhenzi0322 in zhenzi0322

工程目录结构

zhenzi0322
├── pyproject.toml
├── README.rst
├── zhenzi0322
│ └── __init__.py
└── tests
| |__ __init__.py
| |__ test_zhenzi0322.py

pyproject.toml

[tool.poetry]
name = "zhenzi0322"
version = "0.1.0"
description = ""
authors = ["一切皆往事"]

[tool.poetry.dependencies]
python = "^3.7"

[tool.poetry.dev-dependencies]
pytest = "^5.2"

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

测试安装库

安装numpy库

需要先进入工程cd zhenzi0322中,如下:

poetry add numpy

查看pyproject.toml

[tool.poetry]
name = "zhenzi0322"
version = "0.1.0"
description = ""
authors = ["一切皆往事"]

[tool.poetry.dependencies]
python = "^3.7"
numpy = "^1.19.4"

[tool.poetry.dev-dependencies]
pytest = "^5.2"

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

可以看出多了一个numpy = "^1.19.4"

配置poetry安装源

pyproject.toml里添加如下内容:

[[tool.poetry.source]]
name = "tsinghua"
default = true
url = "https://pypi.tuna.tsinghua.edu.cn/simple"

或者使用:https://mirrors.aliyun.com/pypi/simple

poetry虚拟环境管理

创建虚拟环境

方式一(配置文件)

在配置文件pyproject.toml中配置了virtualenvs.create=true,然后执行poetry install时会检查是否有虚拟环境,否则会自动创建。

方式二(poetry)

指定创建虚拟环境时使用的Python解释器版本,如下:

poetry env use python3
  • python3python解释器,相当于cmd下输入python3。还可以指定解释器路径来创建:
poetry env use /home/python.exe

激活虚拟环境

poetry shell

查看虚拟环境信息

poetry env info

显示虚拟环境所有列表

poetry env list

显示虚拟环境绝对路径

poetry env list --full-path

删除虚拟环境

poetry env remove python3

查看python版本

poetry run python -V

poetry扩展命令

安装最新版本的库

poetry add django

安装指定版本的库

poetry add django=2.0

安装pyproject.toml文件中的全部依赖

poetry install

安装开发依赖

poetry add pytest --dev

安装成功后会在pyproject.toml中的[tool.poetry.dev-dependencies]里面。

只安装非development环境的依赖

一般部署时使用,如下:

poetry install --no-dev

更新所有锁定版本的依赖包

poetry update

更新指定依赖包

poetry update django

卸载依赖包

poetry remove django

查看可以更新的依赖包

poetry show --outdated

查看项目安装的依赖包

poetry show

树形结构查看项目安装的依赖包

poetry show -t

运行Python文件

poetry run python main.py
原文地址:https://www.cnblogs.com/zhenzi0322/p/14188895.html