Jupyter無法導入庫,但能在終端導入
?錯誤問題描述:conda activate LLMs
激活某個Conda的環境后,盡管已經通過conda
或者pip
在這個環境中安裝了一些🐍Python的庫,但無法在Jupyter中導入,卻能在終端成功導入。
📚參考自:jupyter notebook添加python內核(windows)
1. 查找錯誤原因
分別在終端和Jupyter中輸入以下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,沒有的話直接安裝。
# 激活目標環境
conda activate LLMs# 查看kernel版本
python -m ipykernel --version# 沒有的話就安裝
# conda install ipykernel -i https://pypi.tuna.tsinghua.edu.cn/simple
在CMD中查看Jupyter kernel list。
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。
{"argv": ["C:\\Users\\ayao5\\miniconda3\\envs\\LLMs\\python.exe","-m","ipykernel_launcher","-f","{connection_file}"],"display_name": "LLMs","language": "python","metadata": {"debugger": true}
}
重啟Jupyter后,即可成功生效。🎉🎉🎉🎉