Poetry 是一個 Python 的套件管理工具,類似於 pip 套件管理,但還提供了建立虛擬環境,還有套件相依性管理,而且 Poetry 入門非常容易,使用過後就回不去 pip + venv,適合新手推薦大家使用 Poerty。
文章目錄
Poetry 安裝
Poetry 安裝需要在 Python 版本 2.7 or 3.5+ 以上
1. Poetry 在 Mac 或 Linux 安裝的朋友:
$ curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python
2. Poetry 在 Windows 安裝的朋友:
$ (Invoke-WebRequest -Uri https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py -UseBasicParsing).Content | python -
3. 查看 Poetry 安裝版本
安裝好 Poetry 後,輸入以下指令,如果看到類似 Poetry 1.1.4
代表安裝成功囉!
$ poetry --version
>> Poetry 1.1.4
4. 如何更新 Poetry 版本
$ poetry self update
5. 如何移除 Poetry 套件
$ python get-poetry.py --uninstall
Poetry 基本操作
1. 初始設定
建立一個新的專案資料夾:
$ poetry new poetry-demo
已經有專案資料夾:
$ cd existing-project
$ poetry init
建立完之後,資料夾結構如下,而其中pyproject.toml
最為重要,
/poetry-tutorial-project
├── README.md
├── poetry_tutorial_project
│ └── __init__.py
├── pyproject.toml
└── tests
├── __init__.py
└── test_poetry_tutorial_project.py
2. 安裝套件
如果要使用 Poetry 安裝套件,只需要輸入poetry add {name}
,而刪除的話則是 poetry remove {name}
,像是我們今天想安裝 black 套件的話:
$ poetry add black
如果在指令後面加上 poetry add {name} --dev
則會在開發環境上安裝指定的套件
- 查看安裝過的套件
poetry show
如果後面加上 --no-dev
的話,則只會顯示正式環境的安裝套件,加上 --tree
的話,則會用樹狀來呈現目前已經安裝的套件
# options
• --no-dev: Do not list the dev dependencies.
• --tree: List the dependencies as a tree.
• --latest (-l): Show the latest version.
4. Poetry 匯出成 requirements.txt
$ poetry export -f requirements.txt --without-hashes > requirements.txt
• --format (-f): The format to export to (default: requirements.txt). Currently, only requirements.txt is supported.
• --output (-o): The name of the output file. If omitted, print to standard output.
• --dev: Include development dependencies.
• --extras (-E): Extra sets of dependencies to include.
• --without-hashes: Exclude hashes from the exported file.
• --with-credentials: Include credentials for extra indices.
5. 安裝 poetry 現有的套件
如果專案中已經有 pyproject.toml 的話,直接 poetry install
就可以囉
6. 開啟 poetry 環境
輸入 poetry shell
開啟虛擬環境,要關閉的話輸入 exit
即可離開
關於 Python 教學的延伸閱讀:
▍本站的其他相關教學:
- [Python教學] 基礎指南全集
- [Python教學] 一切皆為物件,到底什麼是物件 Object ?
- [Python教學] 物件導向 – Class 類的 封裝 / 繼承 / 多型
- [Python教學] 裝飾詞原理到應用
- [Python教學] @property 是什麼? 使用場景和用法介紹
- [Python教學] Class / Static / Abstract Method 初探
- [Python教學] dataclass 是什麼? (python 3.7+)
以上就是 Python 環境管理,讓 poetry 幫你建立虛擬環境的使用教學,希望對你有幫助,那本篇就介紹到這邊,任何問題歡迎底下留言!