Jupyter无法导入库,但能在终端导入的问题

Jupyter无法导入库,但能在终端导入

❌错误问题描述:conda activate LLMs激活某个Conda的环境后,尽管已经通过conda或者pip在这个环境中安装了一些🐍Python的库,但无法在Jupyter中导入,却能在终端成功导入。

📚参考自:jupyter notebook添加python内核(windows)

1. 查找错误原因

分别在终端和Jupyter中输入以下Python代码,获取各自方式Python 解释器的可执行路径。

python 复制代码
import sys
sys.executable

1.1 ✔正确的:在终端的结果

'C:\Users\murphystar\miniconda3\envs\LLMs\python.exe'

1.2 ×错误的:在jupyter中的结果

'C:\Users\murphystar\miniconda3\python.exe'

由此,可以看出Jupyter中的kernel解释器路径并不是已经创建LLMs环境的(尽管我已经安装了ipykernel,也已经选择指定的kernel后仍然无效),而是使用了默认的Python解释器的可执行路径。因此,只需要修改LLMs环境的Python解释器的可执行路径即可。

2. 查看Jupyter kernel list

在CMD中检查该环境下是否有kernel,没有的话直接安装。

powershell 复制代码
# 激活目标环境
conda activate LLMs

# 查看kernel版本
python -m ipykernel --version

# 没有的话就安装
# conda install ipykernel -i https://pypi.tuna.tsinghua.edu.cn/simple

在CMD中查看Jupyter kernel list。

powershell 复制代码
jupyter kernelspec list

输出如下:

Available kernels:
llms C:\Users\murphystar\AppData\Roaming\jupyter\kernels\llms

oe_rdkit C:\Users\murphystar\AppData\Roaming\jupyter\kernels\oe_rdkit

pytorch C:\Users\murphystar\AppData\Roaming\jupyter\kernels\pytorch

python3 C:\Users\murphystar\miniconda3\share\jupyter\kernels\python3

base C:\ProgramData\jupyter\kernels\base

conda C:\ProgramData\jupyter\kernels\conda

假如你的目标环境是LLMs ,则可以去到该kernel目录(C:\Users\murphystar\AppData\Roaming\jupyter\kernels\llms)

下修改kernel.json 文件内容中python解释器的路径为1.1中正确路径:C:\Users\murphystar\miniconda3\envs\LLMs\python.exe

json 复制代码
{
 "argv": [
  "C:\\Users\\ayao5\\miniconda3\\envs\\LLMs\\python.exe",
  "-m",
  "ipykernel_launcher",
  "-f",
  "{connection_file}"
 ],
 "display_name": "LLMs",
 "language": "python",
 "metadata": {
  "debugger": true
 }
}

重启Jupyter后,即可成功生效。🎉🎉🎉🎉

相关推荐
小文数模10 分钟前
2025高教社国赛数学建模C题参考论文(含模型和代码)
python·数学建模·matlab
鸡哥爱技术1 小时前
Django入门笔记
笔记·python·django
猫耳君2 小时前
汽车网络安全 CyberSecurity ISO/SAE 21434 测试之一
python·安全·网络安全·汽车·iso/sae 21434·cybersecurity
勘察加熊人2 小时前
python将pdf转txt,并切割ai
数据库·python·pdf
IMER SIMPLE3 小时前
人工智能-python-深度学习-神经网络VGG(详解)
人工智能·python·深度学习
Dersun3 小时前
python学习进阶之异常和文件操作(三)
开发语言·python·学习·json
Juchecar3 小时前
通过“单词补全”演示 Transformer 原理(Python代码可运行)
人工智能·python
c8i3 小时前
关于python中的钩子方法和内置函数的举例
python
动能小子ohhh4 小时前
AI智能体(Agent)大模型入门【2】--基于llamaindx部署本地的聊天模型。
人工智能·python·aigc·ai编程
MediaTea4 小时前
Python 第三方库:SymPy(符号计算工具)
开发语言·python·数学建模