別先 pip+venv,能跑的第一條是 uv run

能跑腳本的第一條命令是 uv run,不是 python -m venv 加 pip install。

先建 venv 再 pip,腳本常常還沒跑。能執行起來的第一條命令是 uv run。 要對齊一張圖時再 立即開會。

停在這裡:終端已經能跑 uv,uv run example.py 印出 Hello world。檢索詞是 uv run 第一次跑腳本,不用 pip+venv。

install uvuv runHello world
uv run第一條命令
--with臨時依賴
PEP 723寫進腳本頭

先讓 uv 出現在 PATH

  1. 1
    獨立安裝

    macOS / Linux:curl -LsSf https://astral.sh/uv/install.sh | sh。沒有 curl 就用 wget。Windows:powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"。也可以 brew install uv 或 winget install --id=astral-sh.uv -e。

  2. 2
    確認命令

    打開新終端,跑 uv。應看到說明與子命令列表。獨立安裝器之後可用 uv self update。

  3. 3
    寫一個無依賴腳本

    官方例子:print("Hello world") 存成 example.py。

  4. 4
    直接跑

    uv run example.py。成功時印出 Hello world。uv 會自動管理虛擬環境,不必先 python -m venv 再 activate。

有依賴時也不要先 pip

官方腳本指南:缺套件會 ModuleNotFoundError。一次呼叫加上去:uv run --with rich example.py。約束版本用 uv run --with 'rich>12,<13' example.py。多次 --with 可疊幾個套件。

curl -LsSf https://astral.sh/uv/install.sh | sh
uv --version
printf 'print("Hello world")\n' > example.py
uv run example.py

把依賴寫進腳本頭

uv init --script example.py --python 3.12 會依 PEP 723 寫內聯中繼資料。uv add --script example.py 'requests<3' 'rich' 在檔案頂加上 # /// script 的 TOML。之後只要 uv run example.py。需要的 Python 版本沒裝時,uv 會下載。

uv run --with rich example.py
uv init --script example.py --python 3.12
uv add --script example.py 'requests<3' 'rich'
uv run example.py

兩種會讓你以為還要 venv 的情況

專案目錄

在既有專案裡跑獨立腳本,預設會裝目前專案。--no-project 必須在腳本名之前。

pip 介面仍在

uv 提供 pip 相容命令。那是遷移路徑,不是第一次跑腳本的最短路徑。最短路徑是 uv run。

venv 建好了不等於腳本跑過。第一次成功以終端印出 Hello world 為準。

命令對上了,還要把流程攤開: 使用指南 · 立即開會

一定要先裝系統 Python 嗎?

跑 uv 即可。腳本宣告了 requires-python 時,uv run 會尋找並在需要時下載該版本。

--with 和專案依賴會混在一起嗎?

在專案裡,--with 的套件會加在專案依賴之上。只要腳本、不要專案時,加 --no-project。

Windows 怎麼裝?

官方是 powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex",或 winget install --id=astral-sh.uv -e。

內聯中繼資料還要 --no-project 嗎?

不必。官方寫明:有腳本內聯中繼資料時,即使在專案目錄裡也會忽略專案依賴。

立即開會