Skip to content

Instantly share code, notes, and snippets.

@ricferr
Created May 24, 2018 09:13
Show Gist options
  • Save ricferr/90583f608f0b0ae9c3cf6833be04ab85 to your computer and use it in GitHub Desktop.
Save ricferr/90583f608f0b0ae9c3cf6833be04ab85 to your computer and use it in GitHub Desktop.
How to create a systemd service for python script with virtualenv
[Unit]
Description=Some description
After=network.target
[Service]
Type=simple
User=user
WorkingDirectory=/home/user/somedir
Environment=PYTHONPATH=/home/user/somedir
ExecStart=/home/user/venv/bin/python script.py
Restart=on-failure
[Install]
WantedBy=multi-user.target
@641i130
Copy link

641i130 commented May 21, 2021

Thank you this helped me solve an issue I was having!

@load-net
Copy link

[Unit]
Description="run-script"

[Service]
User=root
Group=root
WorkingDirectory=/usr/src/python3.9-venv/
Environment=PATH=/usr/src/python3.9-venv/bin
ExecStart=/bin/sh -c 'cd /usr/src/python3.9-venv/ && source /usr/src/python3.9-venv/bin/activate && python3.9 /usr/src/python3.9-venv/welcomer.py'
Restart=on-failure

[Install]
WantedBy=multi-user.target

@federico-razzoli
Copy link

VIRTUAL_ENV=/home/path/to/venv

@shoguevara you claim that your snippet is tested and works, but this line is not valid syntax.

@shoguevara
Copy link

VIRTUAL_ENV=/home/path/to/venv

@shoguevara you claim that your snippet is tested and works, but this line is not valid syntax.

Worked by the time I've tested it. Moved on since then, I cant even recall what app I was wrapping that time.

@andreabenini
Copy link

Do not use VIRTUAL_ENV var to specify the path, SystemD might complain, use PATH directly and also add /bin/ at the end of it, with your example it might be something like:

...
Environment=PATH=/home/path/to/venv/bin:$PATH
...

@andreabenini
Copy link

@federico-razzoli
Copy link

@andreabenini I don't do it, I just pointed out that it's not valid syntax (Environment= is missing). In my case, systemd didn't complain about that variable, but using it changed nothing. PATH was also not a problem.

@annahri
Copy link

annahri commented Feb 7, 2024

Systemd won't expand variables mentioned in Environment=

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment