close

How to enable a virtualenv in a systemd service unit?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to enable a virtualenv in a systemd service unit in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to enable a virtualenv in a systemd service unit?

  1. How to enable a virtualenv in a systemd service unit?

    While the path for libraries is indeed baked into the python interpreter of the virtualenv, I've had issues with python tools that were using binaries installed in that virtualenv.

  2. enable a virtualenv in a systemd service unit

    While the path for libraries is indeed baked into the python interpreter of the virtualenv, I've had issues with python tools that were using binaries installed in that virtualenv.

Method 1

The virtualenv is “baked into the Python interpreter in the virtualenv”. This means you can launch python or console_scripts directly in that virtualenv and don’t need to activate the virtualenv first or manage PATH yourself.:

ExecStart={{ venv_home }}/bin/fooservice --serve-in-foreground

or

ExecStart={{ venv_home }}/bin/python {{ venv_home }}/fooservice.py --serve-in-foreground

and remove the EnvironmentFile entry.

To verify that it is indeed correct you can check sys.path by running

{{ venv_home }}/bin/python -m site

and comparing the output to

python -m site

Method 2

While the path for libraries is indeed baked into the python interpreter of the virtualenv, I’ve had issues with python tools that were using binaries installed in that virtualenv. For instance, my apache airflow service wouldn’t work because it couldn’t find the gunicorn binary. To work around this, here’s my ExecStart instruction, with an Environment instruction (which sets an environment variable for the service alone).

ExecStart={{ virtualenv }}/bin/python {{ virtualenv }}/bin/airflow webserver
Environment="PATH={{ virtualenv }}/bin:{{ ansible_env.PATH }}"

ExecStartexplicitly uses the python interpreter of the virtualenv. I’m also adding a PATH variable, which adds the binary folder of the virtualenv before the system PATH. That way, I get the desired python libraries as well as binaries.

Note that I’m using ansible to build this service, ergo the curly braces of jinja2.

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read