Skip to content

Instantly share code, notes, and snippets.

@NoifP
Created June 30, 2025 03:55
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')
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])
# the rest of the script!
@NoifP
Copy link
Author

NoifP commented Aug 26, 2025

venv creation (in the same location as your requirements.txt)

python3 -m venv .venv
source .venv/bin/activate
python3 -m pip install -r requirements.txt

@NoifP
Copy link
Author

NoifP commented Aug 26, 2025

your .venv should be created in the same folder as your .py file. If that is not suitable for your project adjust the path on line 7.

@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