iT邦幫忙

1

Python 入門筆記 - 5 - 使用 Poetry 建立虛擬環境與專案管理

  • 分享至 

  • xImage
  •  

🔹 安裝 Poetry

Windows 安裝方式

pip install poetry

Linux/macOS 安裝方式

# 更新系統套件
sudo apt update && sudo apt upgrade -y

# 安裝 Poetry
sudo apt install python3-poetry -y

確認 Poetry 是否安裝成功

poetry --version

🔹 建立 Poetry 虛擬環境

設定 Poetry 讓虛擬環境建立在專案目錄中

poetry config virtualenvs.in-project true

初始化 Poetry 虛擬環境

poetry init

執行後將進入互動式設定

This command will guide you through creating your pyproject.toml config.

Package name [my-project]:
Version [0.1.0]:
Description []:
Author [Your Name <your_email@example.com>, n to skip]:
License []:
Compatible Python versions [^3.10]:

Would you like to define your main dependencies interactively? (yes/no) [yes]

輸入專案名稱、版本、相容的 Python 版本後,Poetry 會自動建立 pyproject.toml 檔案。

檢查虛擬環境資訊

poetry env info

輸出範例

Virtualenv
Python:         3.10.12
Implementation: CPython
Path:           /home/ubuntu/my-project/.venv
Executable:     /home/ubuntu/my-project/.venv/bin/python

若未顯示虛擬環境路徑,可手動建立

poetry env use python3

成功建立後,會顯示虛擬環境的路徑。

🔹 啟動與設定 Python 虛擬環境

啟動虛擬環境

source .venv/bin/activate

安裝專案套件

poetry install

如果只想安裝相依套件(不包含當前專案),可執行

poetry install --no-root

🔹 在 VSCode 中設定 Python 解析器

1️⃣ 按下 Ctrl + Shift + P 開啟命令面板,選擇 Python: Select Interpreter
2️⃣ 選擇工作區層級的 Python 解析器
3️⃣ 選擇 Poetry 虛擬環境的 Python 執行檔

/path/to/project/.venv/bin/python

🔹 啟動開發伺服器(Django 範例)

啟動伺服器

python3 manage.py runserver

允許外部連線

python3 manage.py runserver 0.0.0.0:8000

🔹 移除與重建虛擬環境

移除虛擬環境

poetry env remove python

移除專案設定並重新初始化

rm pyproject.toml poetry.lock
poetry init

🔹 參考文件

Python 官方文件
VSCode Python 擴展文件


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言