Skip to content

uv 메모

Contents

Cheat Sheet

Python versions

Installing and managing Python itself.

  • uv python install: Install Python versions.
  • uv python list: View available Python versions.
  • uv python find: Find an installed Python version.
  • uv python pin: Pin the current project to use a specific Python version.
  • uv python uninstall: Uninstall a Python version.

Scripts

Executing standalone Python scripts, e.g., example.py.

  • uv run: Run a script.
  • uv add --script: Add a dependency to a script
  • uv remove --script: Remove a dependency from a script

Projects

Creating and working on Python projects, i.e., with a pyproject.toml.

  • uv init: Create a new Python project.
  • uv add: Add a dependency to the project.
  • uv remove: Remove a dependency from the project.
  • uv sync: Sync the project's dependencies with the environment.
  • uv lock: Create a lockfile for the project's dependencies.
  • uv run: Run a command in the project environment.
  • uv tree: View the dependency tree for the project.
  • uv build: Build the project into distribution archives.
  • uv publish: Publish the project to a package index.

Tools

Running and installing tools published to Python package indexes, e.g., ruff or black.

  • uvx / uv tool run: Run a tool in a temporary environment.
  • uv tool install: Install a tool user-wide.
  • uv tool uninstall: Uninstall a tool.
  • uv tool list: List installed tools.
  • uv tool update-shell: Update the shell to include tool executables.

The pip interface

Manually managing environments and packages — intended to be used in legacy workflows or cases where the high-level commands do not provide enough control.

Creating virtual environments (replacing venv and virtualenv):

  • uv venv: Create a new virtual environment.

Managing packages in an environment (replacing pip and pipdeptree):

  • uv pip install: Install packages into the current environment.
  • uv pip show: Show details about an installed package.
  • uv pip freeze: List installed packages and their versions.
  • uv pip check: Check that the current environment has compatible packages.
  • uv pip list: List installed packages.
  • uv pip uninstall: Uninstall packages.
  • uv pip tree: View the dependency tree for the environment.

Locking packages in an environment (replacing pip-tools):

  • uv pip compile: Compile requirements into a lockfile.
  • uv pip sync: Sync an environment with a lockfile.

Utility

Managing and inspecting uv's state, such as the cache, storage directories, or performing a self-update:

  • uv cache clean: Remove cache entries.
  • uv cache prune: Remove outdated cache entries.
  • uv cache dir: Show the uv cache directory path.
  • uv tool dir: Show the uv tool directory path.
  • uv python dir: Show the uv installed Python versions path.
  • uv self update: Update uv to the latest version.

Guides

Installing Python

  • 설치 예시: uv python install 3.12
  • 재설치 예시: uv python install --reinstall

    버그 등이 개선됨.

  • 특정 파이썬으로 코드 실행: uvx python@3.12 -c "print('hello world')"

  • 파이썬 버전이 특정되지 않으면 최신 버전이 선택됨. 가령, uv venv 은 최신 파이썬이 선택됨.
  • 시스템에 이미 설치되어 있는 파이썬을 사용하고 싶다면 --no-managed-python 옵션을 사용하면 됨.

Running scripts

  • uv 를 통해 스크립트를 실행하면 uv run 를 통하여 의존성 및 파이썬 환경을 관리하여 실행할 수 있다. 프로젝트 안에서 uv run 을 실행하면 프로젝트의 의존성 및 환경으로 스크립트를 실행해준다. 프로젝트 의존성을 비활성화하려면 --no-project 플래그를 사용하면 됨.

  • 스크립트에 의존성이 없거나, 있어도 os 모듈처럼 표준 라이브러리라면, 단순히 다음과 같이 실행하면 됨.

    uv run example.py
    
  • 프로젝트 안에서, 즉, pyproject.toml 이 있는 디렉토리에서 uv run 을 실행하면 그 프로젝트를 먼저 설치하고 스크립트를 실행해줌. 만약 스크립트가 프로젝트에 의존하지 않으면, 다음과 같이 실행.

    uv run --no-project example.py
    
  • 스크립트에 의존성이 있다면, 파이썬 환경에 의존성이 설치되어야 한다. uv 는 그때그때 수요에 따라 이런 환경을 만든다. 프로젝트나 인라인 메타데이터를 사용하는 것을 권장하지만, 명령을 실행할 때 의존성을 선언할 수 있다.

    uv run --with rich example.py
    uv run --with 'rich>12,<13' example.py # 의존성 버전 설정
    
  • uv run 을 실행하면 디폴트 파이썬 인터프리터가 실행된다. 다음과 같이 파이썬 버전을 설정할 수 있다.

    uv run --python 3.10 example.py
    

스크립트의 의존성 관리

  • 파이썬은 공식적으로 인라인 메타데이터에 대한 표준 형식을 정의했다. 이 표준에 따르면 파이썬 버전과 의존성을 명시할 수 있다. uv init --script 명령어는 스크립트에 인라인 메타데이터를 자동으로 설정해준다.

    uv init --script example.py --python 3.12
    
  • uv add --script 로 의존성을 업데이트할 수 있다. 이렇게 의존성이 인라인 메타데이터로 설정되면 단순히 uv run example.py 로 실행할 수 있다.

    uv add --script example.py 'requests<3' 'rich'
    

    이때, 인라인 메타데이터가 설정된 상태면, uv run 을 프로젝트 안에서 실행하더라도, 인라인 메타데이터가 우선된다. 즉, --no-project 없이도 프로젝트 의존성이 무시된다.

  • 의존성 락킹: 특정 스크립트에 존재하는 인라인 메타데이터를 다음과 같이 uv.lock 파일 포맷으로 락킹할 수 있다. 이 명령어는 example.py.lock 파일을 만든다.

    uv lock --script example.py
    

    lock 파일이 한 번 생성되면, 앞으로 uv 를 실행할 때 이 락킹된 의존성을 재사용하고, 필요하면 업데이트한다.

Working on projects

  • Creating a new project uv init hello-world. 파라미터 없이 단지 uv init 을 실행하면 현재 디렉토리에 프로젝트가 생성된다.

  • 프로젝트 구조

    .python-version uv 가 가상 환경(venv)을 만들 때 어떤 파이썬 버전을 사용할지 정의한다.

    .venv 디렉토리는 프로젝트 가상 환경이다.

    uv.lock 프로젝트의 정확한 의존성을 정의한다.

  • 프로젝트 의존성 관리

    • 의존성 추가

      uv add requests
      uv add 'requests==2.31.0'
      uv add git+https://github.com/psf/requests
      uv add -r requirements.txt -c constraints.txt
      
    • 의존성 제거

      uv remove requests
      
    • 의존성 업그레이드: 호환 가능한 가장 최신 버전으로 업데이트 해줌.

      uv lock --upgrade-package requests
      
  • 명령어 실행

    uv run 으로 프로젝트 환경 안에 있는 임의의 스크립트나 명령어를 실행할 수 있다.

    uv run 은 실행되기 전에 lockfile 이 pyproject.toml 과 최신인지 확인하고, 가상 환경이 lockfile 과 최신인지 확인하여 자동으로 프로젝트 동기화를 유지해준다.

    flask 명령어 실행 예시:

    uv add flask
    uv run -- flask run -p 3000
    

    스크립트 실행 예시:

    uv run example.py
    

    한편, 다음과 같이 uv sync 를 실행하면 수동으로 환경을 업데이트하여, 명령어를 실행하기 전에 업데이트 및 동기화를 할 수 있다.

    uv sync
    source .venv\Scripts\activate
    flask run -p 3000
    python example.py
    
  • Build

    uv build 를 실행하면 dist/ 에 빌드된 결과물이 저장된다.

    uv build <SRC> 특정 디렉토리에 패키지 빌드.

    uv build --package <PACKAGE> 현재 workspace 에 특정 패키지 빌드

  • Publish

    프로젝트를 publish 하기 전에 프로젝트가 패키징될 준비가 되었는지 확인해야 한다. pyproject.toml[build-system] 이 없으면 디폴트로 빌드되지 않는다. 이는 프로젝트가 빌드될 준비가 안되었다는 의미로 간주된다.

    publish 되기를 원치 않는 내부 패키지가 있다면 다음과 같이 private 으로 표시할 수 있다.

    [project]
    classifiers = ["Private :: Do Not Upload"]
    

    uv publish 명령어로 패키지를 publish 할 수 있다. PyPI 토큰을 --token 으로 지정하거나 IP/PW 를 --username--password 로 지정할 수 있다. GitHub 액션으로 publish 하는 경우 credential 이 필요없다.

    PyPI 는 ip/pw 를 지원하지 않는다. 그래서 토큰을 발급받아야 함.

내 패키지 설치

  • 내 패키지가 설치 가능하고 import 가능한지 확인: uv run --with <PACKAGE> --no-project -- python -c "import <PACKAGE>" 이때 --no-project 플래그로 로컬 프로젝트 디렉토리의 패키지가 설치되는 것을 방지함.

    이때, --refresh-package <PACKAGE> 로 캐시를 사용하지 않을 수 있음.

--- Concepts ---

Projects

Project structure and files

  • pyproject.toml: 프로젝트 메타데이터
  • .venv: The project environment. 몇몇 임시 환경을 만들어서 실행하는 명령어 uv run --isolated 같은 것들을 제외하면, uv 는 이 환경을 기반으로 실행된다.

    uv 는 자동으로 가상 환경을 생성하지만, uv sync 로 명시적으로 이 환경을 생성할 수도 있음.

    uv pip install 등으로 프로젝트 환경을 수동으로 조작하는 것은 비추천된다. uv add 를 써라. 단순히 임시적으로 실행되는 의존성이 필요하면 uvxuv run --with 을 써라.

  • uv.lock: uv 는 넓은 범위의 의존성 요구가 정의된 pyproject.toml 를 만들고 lock 파일을 만든다. lock 파일에는 모든 매우 정확하고 구체적인 의존성이 기록된다.

    lock 파일은 uv syncuv run 같은 명령어로 자동으로 업데이트된다. uv lock 으로 명시적으로 업데이트될수도잇다.

Creating projects

uv init 로 프로젝트를 만들 수 있다. 프로젝트는 app 과 lib 으로 구분된다. 디폴트로 app 이 생성된다. lib 을 만드려면 --lib 플래그를 전달하면 됨.

  • app 프로젝트는 웹서버, 스크립트, CLI 같은 프로젝트이다.

  • Packaged applications: app 프로젝트라도 대부분의 경우 패키지를 필요로 한다. 가령 PyPI 에 publish 될 CLI 를 만들 때, 또는 특정 디렉토리에 테스트를 정의하려 할 때가 그렇다.

    --package 플래그를 붙여서 packaged app 프로젝트를 만들 수 있다.

    다음과 같이 명령어가 정의된다.

    다음과 같이 패키지화된 명령어를 실행할 수 있다.

  • lib: 다른 프로젝트에서 사용할 함수나 오브젝트를 제공하는 라이브러리 프로젝트. build 되고 publish 될 용도로 제작되는 프로젝트임.

    --lib 옵션으로 프로젝트를 만들 수 잇음. uv init --lib example-lib 처럼. --lib 옵션은 --package 를 함의한다. 즉, lib 프로젝트는 항상 packaged project 를 만든다.

    py.typed 은 lib 을 읽을 때 타입을 설정함.

    간단한 활용 예시:

Managing dependencies

프로젝트 의존성 설정 필드:

  • project.dependencies: Published dependencies.
  • project.optional-dependencies: Published optional dependencies, or "extras".
  • dependency-groups: Local dependencies for development.
  • tool.uv.sources: Alternative sources for dependencies during development.

uv adduv remove 로 의존성을 관리할 수 잇다. 그러나 의존성 메타데이터를 pyproject.toml 을 직접 업데이트하여 업데이트할수도잇다.

  • 의존성추가: uv add httpx. 이때, --dev, --group, or --optional 옵션을 붙여서 의존성을 관리할 수 잇음.

    의존성 제한 uv add "httpx>=0.20"

    의존성 추가 옵션: uv add -r requirements.txt

  • 의존성 제거: uv remove httpx 마찬가지로 --dev, --group, or --optional 옵션을 사용해서 관리 할 수 잇음.

  • 의존성 변경: 기존 존재하는 의존성을 변경하려면, 가령, 제한을 바꾸려면 uv add "httpx>0.1.0" 와 같이 하면 됨.

    그러나 이는 단지 pyproject.toml 의 제한을 변경할 뿐 lock 된 의존성 버전을 업데이트하진 않음. 의존성이 제한 안에서 최신 버전으로 업데이트하려면 uv add "httpx>0.1.0" --upgrade-package httpx 와 같이 하면됨.

Project dependencies

The project.dependencies table represents the dependencies that are used when uploading to PyPI or building a wheel. Individual dependencies are specified using dependency specifiers syntax, and the table follows the PEP 621 standard.

project.dependencies defines the list of packages that are required for the project, along with the version constraints that should be used when installing them. Each entry includes a dependency name and version. An entry may include extras or environment markers for platform-specific packages. For example:

Dependency sources

The tool.uv.sources table extends the standard dependency tables with alternative dependency sources, which are used during development.

Dependency sources add support common patterns that are not supported by the project.dependencies standard, like editable installations and relative paths. For example, to install foo from a directory relative to the project root:

The following dependency sources are supported by uv:

  • Index: A package resolved from a specific package index. uv add torch --index pytorch=https://download.pytorch.org/whl/cpu
  • Git: A Git repository. uv add git+https://github.com/encode/httpx
  • URL: A remote wheel or source distribution.
  • Path: A local wheel, source distribution, or project directory. uv add /example/foo-0.1.0-py3-none-any.whl

    uv add ~/projects/bar/

  • Workspace: A member of the current workspace.

Development dependencies

https://docs.astral.sh/uv/concepts/projects/dependencies/#development-dependencies

uv add --dev pytest

  • Dependency groups uv add --group lint ruff

    Once groups are defined, the --all-groups, --no-default-groups, --group, --only-group, and --no-group options can be used to include or exclude their dependencies.

    The --dev, --only-dev, and --no-dev flags are equivalent to --group dev, --only-group dev, and --no-group dev respectively.

빌드

uv build

workspace

https://docs.astral.sh/uv/concepts/projects/workspaces/#workspace-layouts

albatross
├── packages
   ├── bird-feeder
      ├── pyproject.toml
      └── src
          └── bird_feeder
              ├── __init__.py
              └── foo.py
   └── seeds
       ├── pyproject.toml
       └── src
           └── seeds
               ├── __init__.py
               └── bar.py
├── pyproject.toml
├── README.md
├── uv.lock
└── src
    └── albatross
        └── main.py