Posts
Search
Contact
Cookies
About
RSS

Auto activating python venv

Added 13 Feb 2024, 9:12 p.m. edited 13 Feb 2024, 9:33 p.m.

In python, the venv module coupled with requirements.txt is the key to making your python creations truly portable, no need for the recipient to pip install guess-the-module-package-names !

That said its all too easy to forget to source your venv, so for convenience I added a facility for a script to auto detect when its run without a virtual environment and source it (that said you'll loose the environment once the script ends)

Initial set up is as per normal

python -m venv venv
. ./venv/bin/activate
pip install -r requirements.txt
ls venv/lib

Yes I know I could be a bit more imaginative with my virtual environment names, the ls command is so you can verify the python version for the venv.

Start your main script with the following code

#!/usr/bin/env python

from activate import activate
activate("venv", "python3.12")

the two parameter are the name of the virtual environment with the last parameter being garnered from the above ls command

all that's left is to show you activate.py

import subprocess
import os

def get_base_prefix_compat():
"""Get base/real prefix, or sys.prefix if there is none."""
return (
getattr(sys, "base_prefix", None)
or getattr(sys, "real_prefix", None)
or sys.prefix
)

def in_virtualenv():
return sys.prefix != get_base_prefix_compat()

def activate(env_name, python_ver):
if not in_virtualenv():
subprocess.run(". ./" + env_name + "/bin/activate", shell = True)
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__),
env_name,
"lib",
python_ver,
"site-packages")))

all you need to do then do is

chmod +x main_script.py

and the script is ready to go...