Last active
January 28, 2026 22:44
-
-
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') | |
| # 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! |
Author
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
your .venv should be created in the same folder as your
.pyfile. If that is not suitable for your project adjust the path on line 7.