pip 再学习

每一次配 python 环境都有新的体验,这里记录一下 pip 的使用方法把。

安装:

pip install

检查依赖有没有冲突,注意,并不是检测过了就能跑(尤其是 tensorflow 的包),但是检测不过几乎一定跑不了。

pip check

列出已经安装的包:

pip list

卸载(一般用不到):

pip uninstall

pip install 本地安装的两种形式:

pip install . 是标准安装,会将源代码复制到 Python 的 site-packages 目录,不会对代码进行任何动态链接,因此每次修改源代码后都需要重新安装包才能生效。
pip install -e . 是开发模式安装,会将代码链接到 Python 环境中,任何对源代码的修改都会立即生效,无需重新安装。

适用场景:
pip install . :适用于你已经准备好一个正式版本的代码并希望安装到环境中,或者你只是想将该包安装到环境中使用。
pip install -e . :适用于开发过程中频繁修改源代码的场景,因为它会保持源代码与环境同步。

查找包的版本:

例如 安装 torchtext:
https://pypi.org/simple/torchtext/
注意看 python 的版本和系统平台。

版本:

在安装一些额外的包时,经常会因为包的问题而头痛,常常需要上 github 找依赖。

这里提供一种方法:
一般我们先确定一些核心包的版本,如:torch, torchvision, torchaudio, torchtext 等
然后 加入 requirements.txt,再加入其它包,不用指定版本,
pip install -r requirements.txt
pip 会自动从高版本开始找,直到版本符合。

当然,对于 cuda 相关的包,需要指定安装源:
--index-url https://download.pytorch.org/whl/cu118
或者
-f https://mirrors.aliyun.com/pytorch-wheels/cu118

pip 的源选项:-i-f--extra-index-url

  • -i:指定主索引地址,等价于 --index-url
    常用于替换默认的 PyPI 源,例如清华镜像,以加快下载速度。
    示例:

    -i https://pypi.tuna.tsinghua.edu.cn/simple
    
  • -f:指定额外的查找链接(--find-links),可以是本地路径或 URL。
    pip 会在该链接指定的 HTML 页面中寻找下载文件链接。适用于私有包或官方未发布到 PyPI 的 wheel 文件。
    示例:

    -f https://mirrors.aliyun.com/pytorch-wheels/cu124
    
  • --extra-index-url:附加一个“次级”索引地址。pip 会先在 --index-url 指定的主源找包,找不到再到 --extra-index-url 指定的源找(这个不一定,会综合考虑)。
    不同于 -f,这个选项要求目标地址是一个符合 PyPI simple API 的索引(即带 /simple/ 的 HTML 页面),不能是纯下载链接列表。
    示例:

    --extra-index-url https://download.pytorch.org/whl/cu124
    

推荐的 requirements.txt 配置示例:

方式 1:使用 -i + -f

--index-url https://pypi.tuna.tsinghua.edu.cn/simple
-f https://mirrors.aliyun.com/pytorch-wheels/cu124

方式 2:使用 --index-url + --extra-index-url

--index-url https://pypi.tuna.tsinghua.edu.cn/simple
--extra-index-url https://download.pytorch.org/whl/cu124
posted @ 2024-11-06 19:22  Cold_Chair  阅读(196)  评论(0)    收藏  举报