1

在 jupyter 中安装 Python 第三方软件包

 8 months ago
source link: https://xujinzh.github.io/2023/10/18/jupyter-install-package/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

在 jupyter 中安装 Python 第三方软件包

发表于2023-10-18|更新于2023-10-18|technologypython
字数总计:849|阅读时长:3分钟|阅读量:52

经常使用 Jupyter 的用户常常着迷于其友好的历史命令记录功能,这样能够非常方便的查看和分享我们在编写和运行代码时都是使用了什么命令,能够很好的用于回顾、排查和分享程序等,如执行该项目安装的软件以及方法等。本篇介绍如何在 jupyter 中安装 Python 第三方软件。

借助 IPython 魔法命令

IPython 是一种基于 Python 交互式解释器,提供了更为强大的编辑和交互功能。在 IPython 中最为重要的就是其提供的魔法命令,Jupyter 使用 IPython 作为其 Python 内核,同样能够使用 IPython 的魔法命令。在 IPython 中有两个 line 魔法命令(以一个 % 开头):%pip%conda

# 安装到当前 jupyter notebook 使用的运行环境
%pip install rich streamlit

# 通过源码安装最新版
%pip install git+https://github.com/huggingface/transformers.git@main

# 通过源码安装指定版,使用 tag 指定安装的版本
%pip install git+https://github.com/huggingface/[email protected]

# 查看使用的 pip 版本和路径
%pip --version

# 如果当前 Python 环境是使用 Anaconda or Miniconda 部署,可以使用 conda 来管理和安装包
%conda install rich streamlit

更多 IPython 的魔法命令请查看:ipython 中的魔法命令

借助 Jupyter 的 ! 修饰符

Jupyter 中提供了 ! 修饰符,能够非常方便的调用 linux shell 命令。但是,该命令是主环境的命令,而不是当前 jupyter notebook 使用的运行环境。一般情况下,我们使用 ipykernel 能够为我们使用的 python 环境创建 jupyter notebook 运行环境:

# 创建新的 Python  环境
conda create -n blip2 python=3.9 -y
conda activate blip2

# 安装 ipykernel
pip install ipykernel ipywidgets
# 创建新的 Jupyter notebook 运行环境,并命名为 huggingface_blip2
# 刷新 jupyter web 页面,在 Jupyter notebook 中创建新的 notebook 时,可以选择该环境:huggingface_blip2
python -m ipykernel install --name hugg_blip2 --display-name "huggingface_blip2"

如果在 Python 环境 blip2 里安装第三方软件,那么我们除了使用上面介绍的 IPython 魔法命令 %pip%conda 外,还可以使用 Jupyter 修饰符 ! 来完成:

import sys

# 此处注意,如果之间用 !pip install package,那么将不是安装到当前 jupyter notebook 运行环境,而是安装到 conda 主环境,我这里是 /opt/miniconda/lib/python3.10/site-packages
!{sys.executable} -m pip install rich streamlit openmim

# 使用 mim 安装 openmmlab 的包 mmdet
!{os.path.join(os.path.dirname(sys.executable), 'mim')} install mmdet

# sys.executable 指定当前运行的 python 路径:'/opt/miniconda/envs/huggingface_blip2/bin/python'
# sys.prefix 指定当前运行的 python 环境路径:'/opt/miniconda/envs/huggingface_blip2'

# 使用 conda 安装包到当前 jupyter notebook 运行环境
!conda install --yes --prefix {sys.prefix} pandas

IPython 魔法命令和 Jupyter !修饰符的区别

两者的区别如下:

  1. % 开头的魔法命令是 Ipython 提供的,而 ! 是 Jupyter 提供的;
  2. % 开头的魔法命令有限,可使用 %lsmagic 查看,! 修饰符开头的可以使用所有 linux shell 命令;
  3. % 开头的魔法命令能够对当前 jupyter notebook 的下面命令产生影响,而 ! 修饰符开头的命令是一次性的,运行时启动一个新进程,结束后不对当前 jupyter notebook 后面的命令产生任何影响

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK