brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's sys.prefix tells a script whether it runs in a virtual environment

Python
~/tips/tip-python-detect-venv-sys-prefix

sys.exit("activate the virtual environment first (source .venv/bin/activate)")

Make a script check that it's running inside a venv before it installs or changes things.

I like setup scripts to refuse to run with the system Python, so they never install packages in the wrong place. The check is one comparison.

import sys

if sys.prefix == sys.base_prefix:
    sys.exit("activate the virtual environment first (source .venv/bin/activate)")

print("running in", sys.prefix)

In a venv, sys.prefix points at the environment folder, like /home/you/project/.venv, while sys.base_prefix still points at the Python install the venv was made from. Outside a venv the two are equal. This is the check the Python docs themselves suggest.

You can do the same from the shell for a quick look:

python3 -c 'import sys; print(sys.prefix != sys.base_prefix)'

Some guides check the VIRTUAL_ENV environment variable instead. I don’t trust that as much: it’s only set by the activate script, so running .venv/bin/python directly, which is what cron jobs and systemd units do, leaves it empty even though you’re in the venv. It can also linger from a shell where you forgot to deactivate.

Conda environments work differently and don’t always pass this test. If your users run conda, check CONDA_PREFIX as well.

Further reading: sys.prefix, venv: how venvs work

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link