Skip to content

Instantly share code, notes, and snippets.

@NoifP
Last active January 28, 2026 22:44
Show Gist options
  • Select an option

  • Save NoifP/a38549bd2a2305e3d107a6b2d10233d5 to your computer and use it in GitHub Desktop.

Select an option

Save NoifP/a38549bd2a2305e3d107a6b2d10233d5 to your computer and use it in GitHub Desktop.
Python3 auto load .venv without hard coded path in shebang
#!/usr/bin/env python3
# activate .venv without having to change shebang for different install location
import sys
import os
python_venv = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.venv/bin/python3')
# confirm python3 exists in .venv before trying to load it!
if os.path.isfile(python_venv):
if sys.executable != python_venv:
print(f"Launched with {sys.executable}. Relaunching {python_venv} to load .venv")
os.execv(python_venv, [python_venv, *sys.argv])
else:
print(f"\n{python_venv} not found. Have you setup a .venv?")
print("Run the following commands from this script's path to do the initial setup:\n")
print("python3 -m venv .venv")
print("source .venv/bin/activate")
print("python3 -m pip install -r requirements.txt\n")
exit(1)
# the rest of the script!
@NoifP
Copy link
Author

NoifP commented Sep 15, 2025

If using debian you may also need to do apt install python3-venv before doing the .venv creation.

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