Auto Python Venv
For a few python scripts, I forget that I need to activate the python venv before running them. So I write the following code that can be put at the top of a script. If an import statement fails it will spawn a new shell and activate the venv, then run the script in that shell.
The import statements which show the issue, should be wrapped in the try … except block show here
import sys
try:
import <stuff installed with venv pip>
except ModuleNotFoundError:
from pathlib import Path
scriptPath = Path(__file__)
scriptDir = scriptPath.parent
possLocations = [ scriptDir / '.venv' / 'bin' / 'activate', scriptDir / 'bin' / 'activate']
activatePath = False
for possibility in possLocations:
if possibility.is_file():
activatePath = possibility
break
if activatePath:
args = sys.argv[1:] if len(sys.argv) > 1 else ['']
resp = os.system(f". {activatePath} && {scriptPath} {' '.join(args)}")
sys.exit(os.waitstatus_to_exitcode(resp))
else:
print(f"cannot find activate in usual locations under {scriptDir}")
sys.exit(1)