Open4

uvの docs を読む

ikeponikepon

uv から Python のバージョン管理

  • 今まで pyenv を使ってたけど、それは必要なくなる
# 最新の Python バージョンをインストール
uv python install

# バージョンを指定した Python install
uv python install 3.12

# install されている Python のバージョンチェック
uv python list
ikeponikepon

uv から Python script を実行

  • uv からスクリプト実行
uv run example.py

# 引数がある場合
uv run example.py test test2
# 引数を受けるスクリプト
import sys

# この `sys.argv[1:]` で受ける、このケースでは受け取ったものを全て表示してる
# `sys.argv[0]` は一つ目の引数でこのケースだと `example.py` になる
print(" ".join(sys.argv[1:]))

uv run 実行時に pyproject.toml があるディレクトリで実行した時、スクリプト実行前にプロジェクト関連ライブラリはインストールされる
不要な場合は --no-project フラグをつける

uv run 実行時に python のバージョンを指定できる、これは良さそう

# Use a specific Python version
uv run --python 3.10 example.py
  • uv からスクリプト作成

    • Python のバージョンもしてできそう
      • そのバージョンがインストールされてなかったらどうなるかは不明(勝手にインストールされる?)
    • ファイルも / で区切ればディレクトリ以下におくし、なければ作成されそう
uv init --script example.py --python 3.12

ファイルを作っておいて、そのファイルに対して依存ライブラリを追加できそう
以下を実行するとファイルの metadata の ///script に追加される
( uv will automatically create an environment with the dependencies necessary to run the script )

-> ってことは、 Python のバージョンも自動でやってくれる気がする
(.uv run will search for and use the required Python version. The Python version will download if it is not installed )

uv add --script example.py 'requests<3' 'rich'
# /// script
# dependencies = [
#   "requests<3",
#   "rich",
# ]
# ///

import requests
from rich.pretty import pprint

resp = requests.get("https://peps.python.org/api/peps.json")
data = resp.json()
pprint([(k, v["title"]) for k, v in data.items()][:10])
ikeponikepon
  • tools
    • uvx コマンドを使うとインストールせずに実行できる
      • uvx ruff : ruff をインストールなしで実行できる
        • 一時的に別環境にインストールされて使える
      • uvxuv tool run ruff の alias
      • 引数も tool name の後に置けば取れる
    • project 内のライブラリを使いたい場合は uv run を使う
    • tool は project から隔離された仮想環境で実行される
      • the tool will be run in a virtual environment that is isolated from your project.

    • package name と command name が違う場合は --from を使う
      • uvx --from httpie http
      • 上記は httpie パッケージから http コマンドを使う
    • tool でよく使うものは uv tool install ruff みたいにインストールしておけば、それ以降は uv を省略して ruff コマンドとして使える
      • その場合、 PATH で指定した場所にインストールされる
      • インストールされてかなったら warning が出るので、 uv tool update-shell でインストールが可能
      • これは scripts や project とは別環境になっている