Created
June 30, 2025 03:55
-
-
Save NoifP/a38549bd2a2305e3d107a6b2d10233d5 to your computer and use it in GitHub Desktop.
Python3 auto load .venv without hard coded path in shebang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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! |
Author
Author
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.
Author
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
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