Pyenv环境Jupyter Notebook在Systemd中仅调用系统Python的问题
Hey there, let's dig into why your systemd service is falling back to the system Python instead of your pyenv-managed Jupyter environment. The core issue here is that systemd runs services in a stripped-down environment—it doesn't inherit the shell variables (like your custom PATH) from your .bashrc/.zshrc or interactive console sessions. That's why your manual console setup works, but the service doesn't.
Here's how to fix it step by step:
Systemd needs explicit instructions to use your pyenv environment. Let's make a user-level service file (so you don't need sudo privileges):
Create the service file in your user's systemd directory:
nano ~/.config/systemd/user/jupyter-notebook.servicePaste in this configuration, adjusting paths to match your setup:
[Unit] Description=Pyenv Jupyter Notebook Service After=network.target [Service] User=mortenb # Explicitly set PATH to prioritize your pyenv environment's bin folder Environment="PATH=/home/mortenb/.pyenv/versions/jupyter/bin:/usr/bin:/bin" # Use the absolute path to your pyenv Jupyter executable ExecStart=/home/mortenb/.pyenv/versions/jupyter/bin/jupyter-notebook --config=/etc/jupyter/jupyter_notebook_config.py # Set your preferred working directory (optional, adjust as needed) WorkingDirectory=/home/mortenb # Optional: Auto-restart if the service crashes Restart=always [Install] WantedBy=default.target
Once the service file is saved, run these commands to apply the changes:
# Reload systemd to recognize the new service systemctl --user daemon-reload # Enable the service to start on boot (optional) systemctl --user enable jupyter-notebook.service # Start the service immediately systemctl --user start jupyter-notebook.service
To make sure everything's working:
- Check the service status:
systemctl --user status jupyter-notebook.service - View the service logs to confirm it's using the correct Python:
Look for lines that reference Python 3.6.5 or your pyenv environment path.journalctl --user -u jupyter-notebook.service - Open Jupyter Notebook and run
!python --versionin a cell—it should show 3.6.5 as expected.
- Never rely on shell environment variables in systemd services: Systemd doesn't load
.bashrc/.zshrc, so you must define all necessary variables (likePATH) directly in the service file. - Use absolute paths: Always point to the full path of your pyenv
jupyter-notebookexecutable to avoid ambiguity. - User vs System Services: We used a user-level service here because it's tied to your account and avoids root permissions. If you need a system-wide service, place the file in
/etc/systemd/system/and adjust theUserfield appropriately.
内容的提问来源于stack exchange,提问作者MortenB

