jupter 如何使用 python3 虚拟空间

背景和价值

在 Jupyter 中使用 Python3 虚拟环境的步骤如下(比 Python2 更简单,因为 Python3 内置了 venv 模块):


步骤 1:创建 Python3 虚拟环境

# 创建一个名为 `myenv_py3` 的虚拟环境(名字可自定义)
python3 -m venv myenv_py3

步骤 2:激活虚拟环境

  • Windows (PowerShell):
    .\myenv_py3\Scripts\Activate.ps1
    
  • macOS/Linux (Bash):
    source myenv_py3/bin/activate
    

步骤 3:安装 ipykernel 到虚拟环境

pip install ipykernel

步骤 4:将虚拟环境注册到 Jupyter

python -m ipykernel install --user --name=myenv_py3
  • --name=myenv_py3 是 Jupyter 中显示的内核名称(可自定义)。

步骤 5:在 Jupyter 中使用虚拟环境

  1. 启动 Jupyter Notebook:
    jupyter notebook
    
  2. 新建 Notebook 时,选择内核 myenv_py3
  3. 在 Notebook 中验证 Python 版本:
    import sys
    print(sys.version)  # 应显示虚拟环境中的 Python3 路径
    

常见问题

  1. 虚拟环境未出现在 Jupyter 中?

    • 确保在虚拟环境中执行了 ipykernel 的安装和注册命令。
    • 重启 Jupyter 服务并刷新页面。
  2. Jupyter 仍使用系统 Python?

    • 检查虚拟环境是否激活(命令行前缀应有 (myenv_py3))。
    • 重新运行注册命令:python -m ipykernel install --user --name=myenv_py3

删除虚拟环境内核(如果需要)

jupyter kernelspec uninstall myenv_py3

通过这种方式,你可以为不同项目创建独立的 Python3 环境,并在 Jupyter 中灵活切换。

参考资料

posted @ 2025-03-18 15:34  向着朝阳  阅读(27)  评论(0)    收藏  举报