Created
June 18, 2024 13:03
-
-
Save Jip-Hop/15aa2b9bf9134242ad00bac5f021bc7c to your computer and use it in GitHub Desktop.
Python script which installs packages it requires with pip inside a venv that's created on the fly.
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 | |
import os | |
import sys | |
__requirements__ = {"docker==7.1.0"} | |
def _setup_env(): | |
venv = os.path.join(os.path.dirname(__file__), ".venv") | |
if not os.path.exists(venv): | |
from venv import create | |
create(venv, with_pip=True) | |
# Re-run under the python in venv | |
# https://stackoverflow.com/a/77635818 | |
if "VIRTUAL_ENV" not in os.environ: | |
new_python = os.path.join(venv, "bin", "python") | |
args = [new_python] + sys.argv | |
os.environ["VIRTUAL_ENV"] = venv | |
os.execv(new_python, args) | |
# Install required packages in venv | |
# https://stackoverflow.com/a/78407952 | |
import subprocess | |
import importlib.metadata | |
installed = { | |
f"{package.name}=={package.version}" | |
for package in importlib.metadata.distributions() | |
} | |
missing = __requirements__ - installed | |
if missing: | |
print("Installing missing python package(s):", missing) | |
subprocess.check_call( | |
[sys.executable, "-m", "pip", "install", "--upgrade", "pip"] | |
) | |
subprocess.check_call([sys.executable, "-m", "pip", "install", *missing]) | |
def main(): | |
_setup_env() | |
print("TODO: start the real work from here") | |
if __name__ == "__main__": | |
try: | |
main() | |
except KeyboardInterrupt: | |
sys.exit(130) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment