Python中如何在Ubuntu下将Jupyter Notebook加入/etc/rc.local随系统启动,并解决Anaconda环境无法被Jupyter使用的问题

每次启动 jupyter notebook 使用的还是系统自带的 python3
我运行
import sys
for line in sys.path:
print(line)
输出结果是:
/usr/lib/python36.zip
/usr/lib/python3.6
/usr/lib/python3.6/lib-dynload

/usr/local/lib/python3.6/dist-packages
/usr/lib/python3/dist-packages
/usr/local/lib/python3.6/dist-packages/IPython/extensions
/root/.ipython



如果 ssh 登录进去运行 jupyter notebook --allow-root
再远程访问使用的就是我安装的 anconda
再运行上面的代码输出是
/var/jupyter_nb
/root/anaconda3/lib/python37.zip
/root/anaconda3/lib/python3.7
/root/anaconda3/lib/python3.7/lib-dynload

/root/anaconda3/lib/python3.7/site-packages
/root/anaconda3/lib/python3.7/site-packages/IPython/extensions
/root/.ipython

不知需要怎么设置才能每次让 jupyter notebook 系统自动重启加载后使用 Anconda 而不是系统自带的 python3,请教大家了。
Python中如何在Ubuntu下将Jupyter Notebook加入/etc/rc.local随系统启动,并解决Anaconda环境无法被Jupyter使用的问题


6 回复

systmctl 了解一下


帖子回复:

要在Ubuntu下让Jupyter Notebook随系统启动,并确保它使用Anaconda环境,可以按以下步骤操作。注意,现代Ubuntu版本(18.04+)通常使用systemd而不是rc.local,但两种方法我都会说明。

方法一:使用systemd(推荐)

  1. 创建systemd服务文件

    sudo nano /etc/systemd/system/jupyter.service
    
  2. 写入以下内容(根据你的环境修改路径和用户名):

    [Unit]
    Description=Jupyter Notebook
    After=network.target
    
    [Service]
    Type=simple
    User=你的用户名
    Environment="PATH=/home/你的用户名/anaconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
    ExecStart=/home/你的用户名/anaconda3/bin/jupyter notebook --config=/home/你的用户名/.jupyter/jupyter_notebook_config.py
    WorkingDirectory=/home/你的用户名
    Restart=always
    RestartSec=10
    
    [Install]
    WantedBy=multi-user.target
    
  3. 启用并启动服务

    sudo systemctl enable jupyter.service
    sudo systemctl start jupyter.service
    

方法二:使用rc.local(旧版Ubuntu)

  1. 编辑rc.local文件

    sudo nano /etc/rc.local
    
  2. exit 0之前添加

    su - 你的用户名 -c "/home/你的用户名/anaconda3/bin/jupyter notebook --config=/home/你的用户名/.jupyter/jupyter_notebook_config.py &"
    
  3. 确保rc.local可执行

    sudo chmod +x /etc/rc.local
    

解决Anaconda环境问题

确保Jupyter能识别Anaconda环境,需要在启动前激活环境。最简单的方法是在Jupyter配置中设置正确的PATH,或者使用conda安装nb_conda

conda install nb_conda

这会让Jupyter自动检测所有conda环境。

总结:用systemd更可靠,装nb_conda解决环境识别。

建议 supervisord

先 source /root/anaconda3/bin/activate ?

谢谢楼上各位,我试一下

systmctl 搞定了,再次谢谢楼上两位

回到顶部