Skip to content

Instantly share code, notes, and snippets.

@pgmac
Created June 14, 2025 12:43
Show Gist options
  • Select an option

  • Save pgmac/0bc0da3df511ca58993ec5416950a04d to your computer and use it in GitHub Desktop.

Select an option

Save pgmac/0bc0da3df511ca58993ec5416950a04d to your computer and use it in GitHub Desktop.
Auto activating a python virtualenv
from subprocess import run
from os import path, getenv
import sys
DEBUG = getenv('DEBUG', False)
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():
print(f" sys.prefix: {sys.prefix}\nbase_prefix: {get_base_prefix_compat()}") if DEBUG else None
return sys.prefix != get_base_prefix_compat()
def activate(env_name, python_ver = f"python{sys.version_info.major}.{sys.version_info.minor}"):
if not in_virtualenv():
pyactivate_path = path.abspath(path.join(path.dirname(__file__),
env_name,
"bin",
"activate"))
pypath = path.abspath(path.join(path.dirname(__file__),
env_name,
"lib",
python_ver,
"site-packages"))
try:
print(f"source {pyactivate_path}") if DEBUG else None
run(f"source {pyactivate_path}", shell = True)
print(f"Prepending to path: {pypath}") if DEBUG else None
sys.path.insert(0, pypath)
except Exception as e:
print(f"Error activating virtual environment: {e}")
sys.exit(1)
#!/usr/bin/env python3
''' A quick script that just does nothing - just to show this off
Shows off single parameter call
'''
# Need to do this first so you will find your modules
from activate import activate
activate(".venv") # First param is the virtualenv directory, second optional param is the python version
import simple_term_menu # Import virtualenv modules
if __name__ == __main__:
print("Here I am")
#!/usr/bin/env python3
''' A quick script that just does nothing - just to show this off.
Shows off 2 parameters call
'''
# Need to do this first so you will find your modules
from activate import activate
activate(".venv", "python3.13") # First param is the virtualenv directory, second optional param is the python version
import simple_term_menu # Import virtualenv modules
if __name__ == __main__:
print("Here I am")
@pgmac
Copy link
Copy Markdown
Author

pgmac commented Jun 14, 2025

Some people exist an example of what NOT to do.
Don't do this gumph.

Use uv instead
https://docs.astral.sh/uv/guides/scripts/#declaring-script-dependencies

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