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