[已解决] error: metadata-generation-failed + This package requires Rust and Cargo to compile extensions

1 日志

Collecting safetensors
  Downloading http://mirrors.aliyun.com/pypi/packages/71/7e/2d5d6ee7b40c0682315367ec7475693d110f512922d582fef1bd4a63adc3/safetensors-0.5.3.tar.gz (67 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 67.2/67.2 kB 28.9 MB/s eta 0:00:00
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... error
  error: subprocess-exited-with-error
  
  × Preparing metadata (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [6 lines of output]
      
      Cargo, the Rust package manager, is not installed or is not on PATH.
      This package requires Rust and Cargo to compile extensions. Install it through
      the system's package manager or via https://rustup.rs/
      
      Checking for Rust toolchain....
      [end of output]
  
  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

2 分析

可以看到在安装依赖(例如 safetensors 包)时,需要用到 Rust 语言的编译工具链,而系统中没有安装 Rust 或者 Cargo 没有配置到 PATH 环境变量中所导致的。为了解决这个问题,可以按照以下步骤操作:

  1. 安装 Rust
    使用 rustup 安装 Rust 和 Cargo。你可以在终端执行以下命令:

    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

    会出现:

    1) Proceed with standard installation (default - just press enter)
    2) Customize installation
    3) Cancel installation
    >

    按照提示选择默认(直接回车)安装,会出现提示:

    stable-x86_64-unknown-linux-gnu installed - rustc 1.85.0 (4d91de4e4 2025-02-17)
    
    
    Rust is installed now. Great!
    
    To get started you may need to restart your current shell.
    This would reload your PATH environment variable to include
    Cargo's bin directory ($HOME/.cargo/bin).
    
    To configure your current shell, you need to source
    the corresponding env file under $HOME/.cargo.
    
    This is usually done by running one of the following (note the leading DOT):
    . "$HOME/.cargo/env"            # For sh/bash/zsh/ash/dash/pdksh
    source "$HOME/.cargo/env.fish"  # For fish

    安装完成后建议重启终端,推荐按照提示执行:(可参考-linux永久环境变量添加教程)

    source $HOME/.cargo/env

    这样可以确保 Cargo 已经加入到 PATH 环境变量中

  2. 验证安装
    执行下面的命令检查是否安装成功:

    cargo --version rustc --version

    如果命令能正确显示版本信息,说明 Rust 工具链已经成功安装

  3. 重新安装依赖
    安装完 Rust 工具链后,再次运行安装命令:(以下只是个范例)

    pip install -r docs/requirements.txt

    此时安装过程应该能够顺利编译出所需的扩展模块,不再出现之前的错误

  4. 其他方案(下下策,还是推荐把环境配齐的)
    如果你不需要 safetensors 包提供的功能,也可以考虑从 requirements.txt 中移除这个依赖,但一般建议安装好 Rust 工具链以保证依赖完整

这样操作后,成功解决问题