poetry介紹
poetry
是一個Python
虛擬環境和依賴管理的工具。poetry
和pipenv
類似,另外還提供了打包和發布的功能。
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
python3
是python
解釋器,相當於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