Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a python script in a local conda env into systemd service in Linux?

I have a daemon Python script in my conda environment which I run it:

source activate my_env
python my_server.py 

I would like to convert it to as systemd service, so I created my_server.service file:

[Service]
User=myuser
Group=myuser
Type=simple
ExecStart=/home/myuser/.conda/envs/my_env/bin/python /path/to/my_server.py

This does not work because the systemd is being run as the root user and I can not activate the conda environment to get the all path right. What is the correct way to create a systemd service when the executable requires a specific conda env to run?

like image 774
motam79 Avatar asked Dec 26 '18 06:12

motam79


People also ask

How do I run a Python script in conda environment?

Create required Anaconda environment conda create --name environmentName python=3 pandas numpy . Include all your dependencies at once while creating the environment. Switch to the environment with conda activate environmentName . Executing the python script python fileName.py .

Can you use conda with VENV?

1.No, if you're using conda, you don't need to use any other tool for managing virtual environments (such as venv, virtualenv, pipenv etc).


1 Answers

You can run systemd services on user level instead of running on system level, which will run it as root user. Instead of putting the .service file on /etc/systemd/system directory, you have put the file inside ~/.config/systemd/user/ directory and no need of User and Group derivative. For example:

[Unit]
Description=Description
After=network.target

[Service]
Type=simple
WorkingDirectory=/path/to/
ExecStart=/home/myuser/.conda/envs/my_env/bin/python my_server.py

[Install]
WantedBy=default.target

Instead of starting this service with privileged permission, you can start with the running user permission using systemctl --user start/restart/stop servicename command. No need of sudo privilege or password.

like image 75
arryph Avatar answered Oct 15 '22 17:10

arryph