我们在开发中往往会用的不同版本的 Python ,但 Notebook 默认提供的 Python 版本有限,有时候并不一定是我们需要的,那怎样快速创建一个我们需要的 Python 版本呢? 本教程的思路就是通过内置的 conda 安装和切换 Python ipykernel,通过创建 kernel.json 挂载到可选 kernel。
首先创建虚拟环境:
!/home/ma-user/anaconda3/bin/conda create -n python-3.10.10 python=3.10.10 -y --override-channels --channel https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
!/home/ma-user/anaconda3/envs/python-3.10.10/bin/pip install ipykernel
接着通过 echo ${path}
获取已有的环境变量,并替换下文中 env 的 /home/ma-user/anaconda3/envs/python-3.10.10/bin:
后面部分,将我们的环境变量添加 python-3.10.10 。
接着将虚拟环境挂载到 kernel:
import json
import os
data = {
# kernel 显示的名称
"display_name": "python-3.10.10",
# 上面创建的虚拟环境路径
"env": {
"PATH": "/home/ma-user/anaconda3/envs/python-3.10.10/bin:/home/ma-user/anaconda3/envs/python-3.7.10/bin:/modelarts/authoring/notebook-conda/bin:/opt/conda/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/ma-user/modelarts/ma-cli/bin:/home/ma-user/modelarts/ma-cli/bin:/home/ma-user/anaconda3/envs/PyTorch-1.8/bin"
},
# 人生苦短,我用python
"language": "python",
# 执行参数
"argv": [
"/home/ma-user/anaconda3/envs/python-3.10.10/bin/python",
"-m",
"ipykernel",
"-f",
"{connection_file}"
]
}
if not os.path.exists("/home/ma-user/anaconda3/share/jupyter/kernels/python-3.10.10/"):
os.mkdir("/home/ma-user/anaconda3/share/jupyter/kernels/python-3.10.10/")
with open('/home/ma-user/anaconda3/share/jupyter/kernels/python-3.10.10/kernel.json', 'w') as f:
json.dump(data, f, indent=4)
创建完成后,稍等片刻,或刷新页面,点击右上角 kernel 选择 python-3.10.10 :
最后,我们验证一下环境是否启用成功。
!python -V
!pip -V
# 输出
ython 3.10.10
pip 23.3.1 from /home/ma-user/anaconda3/envs/python-3.10.10/lib/python3.10/site-packages/pip (python 3.10)
之后我们就能快速开始其他开发流程了,比如 大模型 API 调用从 0 到 1
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有