Python

发布于 更新于

AI总结: 本文介绍了如何安装和使用uv工具,包括通过curl、wget和PowerShell进行安装的方法。对于新项目,可以使用uv init命令快速生成项目结构,并创建虚拟环境。现有项目则可以通过uv init和uv run命令生成环境,并添加依赖。依赖同步和升级可以通过uv sync和相关命令实现,此外,还可以重新生成requirements.txt文件,检测和升级依赖,查看依赖树,以及切换Python版本。最后,用户可以使用deptry工具检测无用依赖。改进建议包括提供更多示例和详细的错误处理说明,以帮助用户更好地理解和使用这些命令。
  • 安装uv
curl -LsSf https://astral.sh/uv/install.sh | sh  
wget -qO- https://astral.sh/uv/install.sh | sh  
powershell -c "irm https://astral.sh/uv/install.ps1 | iex"  
  • 新项目
    使用 uv init 命令快速生成项目结构和配置(如 pyproject.toml.python-version):

    uv init my_project  
    cd my_project  
    
    uv venv --python 3.11 .venv   # 默认生成 .venv 目录  
    # 或自定义名称  
    uv venv --python 3.12 my_env  # 创建名为 my_env 的环境  
    
    source .venv/bin/activate       
    

  • 现有项目

    cd existing_project  
    uv init  
    uv run              # 生成 .venv 环境  
    uv add flask  
    uv add -r requirements.txt  
    uv add --requirements requirements.txt    # 将requirements.txt中依赖信息同步到pyproject.toml文件中  
    

  • 依赖同步
    对于已有 pyproject.tomluv.lock 的项目,快速同步环境:

    uv sync  
    uv sync --upgrade  # 升级依赖包, 需要在pyproject.toml中配置的版本号>=  
    

  • 重新生成requirements.txt

    uv pip freeze > requirements.txt  
    

  • 检测并升级依赖

    uv pip list --outdated  
    uv pip install --upgrade urllib3  
    

  • 查看依赖树

    uv tree  
    

  • Python 版本切换

    # 指定安装镜像 默认到github下载, 使用时查询当前可用的加速镜像地址  
    export UV_PYTHON_INSTALL_MIRROR=https://github.com/indygreg/python-build-standalone/releases/download  
    uv python install 3.11    # 安装指定版本  
    uv python use 3.11        # 切换当前环境版本  
    

  • 检测无用依赖

uv pip install deptry

# deptry .  
Scanning 7 files...  

pyproject.toml: DEP002 'flask' defined as a dependency but not used in the codebase  
pyproject.toml: DEP002 'loguru' defined as a dependency but not used in the codebase  
Found 2 dependency issues.