Skip to content

Instantly share code, notes, and snippets.

@Jip-Hop
Created June 18, 2024 13:03
Show Gist options
  • Select an option

  • Save Jip-Hop/15aa2b9bf9134242ad00bac5f021bc7c to your computer and use it in GitHub Desktop.

Select an option

Save Jip-Hop/15aa2b9bf9134242ad00bac5f021bc7c to your computer and use it in GitHub Desktop.

Revisions

  1. Jip-Hop created this gist Jun 18, 2024.
    54 changes: 54 additions & 0 deletions install_and_run.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,54 @@
    #!/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)