Contents

python專案架構

venv

創造一個虛擬環境,讓各種庫不影響整台電腦,只存在於這個專案的.venv資料夾中。

1
python -m venv .venv

啟動虛擬環境:

1
2
3
4
5
# powershell
.venv\Scripts\Activate.ps1

# cmd
.venv\Scripts\activate.bat

requirements

生成requirements.txt

1
pip freeze > requirements.txt

安裝:

1
pip install -r requirements.txt

requirements.txt最大的問題在於不會分辨library的直接依賴和間接依賴,因此當不使用一個library時,它原本依賴的那些library還是會被留在requirements.txt中。因此現在主流的解決方案是使用pyproject.toml

pyproject

在專案中新增一個叫做pyproject.toml的檔案。

範例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
[project]
name = "proj"
version = "0.1.0"
requires-python = ">=3.13"
description = "A simple python project."
readme = "README.md"
keywords = ["egg", "bacon", "sausage"]
dependencies = [
	"bs4==0.0.2"
]

安裝:

1
pip install -e .

uv

uvvenvpyproject.toml與開發者間的橋樑,提供了一個方便、整合的解決方案。

安裝uv:

1
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

創建pyproject.toml

新增library:

1
uv add bs4

安裝(記得保留uv.lock):

1
uv sync

Run:

1
uv run main.py

uv會自動進入對應的虛擬環境並執行。

References