[note] Python uv
- Installation and Shell autocompletion
- 安裝 uv 的方式
- 安裝 shell autocompletion 的方式
- Features
Python 版本管理(uv python
)
# https://docs.astral.sh/uv/getting-started/features/#python-versions
$ uv python list # 檢視可以安裝的 Python 版本
$ uv python install 3.12 # 安裝特定 Python 版本
# 問題解決
$ uv python install --reinstall # 重新安裝
Python Script(uv run
)
# https://docs.astral.sh/uv/guides/scripts/
# 建立 Python Script
$ uv init --script example.py --python 3.12
# 定義 dependencies:使用 inline metadata format 來定義該 script 需要用到的套件
$ uv add --script example.py 'requests<3' 'rich'
# 如果使用 inline metadata,uv run 時會自動使用對應的 Python 版本並安裝相依套件
# uv run <xxx.py>
$ uv run example.py
# 鎖套件版號
$ uv lock --script
使用工具(uvx
)
# https://docs.astral.sh/uv/guides/tools/
# uvx [tool_name] 等同於 uv tool run [tool_name]
$ uvx ruff check
$ uvn ruff@latest check # 指定套件版本
# 對於某些 tool 名稱和 command 名稱不同的工具,需要使用 --from
$ uvx --from httpie http # http 這個 command 是來自 httpie 這個套件
# 如果需要指定套件版本,也可以用 --from
$ uvx --from 'ruff==0.3.0' ruff check
$ uvx --from 'ruff>0.2.0,<0.3.0' ruff check
# 對於經常會使用到的 Command Line Tool,可以安裝到本機,未來就可以直接使用,不需要在輸入 uvx
$ uv tool install ruff
$ uv tool upgrade ruff # 更新 tool
$ uv tool upgrade --all # 更新所有 tool
管理 Project
# https://docs.astral.sh/uv/guides/projects/
$ uv init
$ uv init <package-name>
$ uv venv # 建立虛擬環境
$ uv add <package1> <package2>
$ uv remove <package>
$ uv lock --upgrade-package <package> # 更新套件
$ uv run -- flask run -p 3000 # 執行指令
$ uv run example.py # 執行 script
PIP 的支援
# https://docs.astral.sh/uv/getting-started/features/#the-pip-interface
# 把原本在 requirement.txt 中訂一個的 packages 安裝到專案中
$ uv pip install -r ./requirements.txt