Daily Shaarli

All links of one day in a single page.

September 25, 2024

Python venv
#!/usr/bin/env python3

class Venv():
    def __init__(self, path, verbose=2, requires=[], libs=[]):
        """Creates a virtual environment in the specified directory."""
        import venv
        import os
        import site
        import sys

        venv_dir = os.path.abspath(path)
        builder = venv.EnvBuilder(with_pip=True)
        builder.create(venv_dir)

        psep = os.pathsep
        bin_dir = os.path.join(venv_dir, "bin")
        path = psep.join([bin_dir, *os.environ.get("PATH", "").split(psep)])
        os.environ["PATH"] = path
        os.environ["VIRTUAL_ENV"] = venv_dir
        os.environ["VIRTUAL_ENV_PROMPT"] = os.path.basename(venv_dir)
        # add the venvs libraries to the host python import mechanism
        prev_length = len(sys.path)
        for lib in libs + [
            os.path.join(
                venv_dir, "lib",
                f"python{sys.version_info.major}.{sys.version_info.minor}",
                "site-packages"
            ),
        ]:
            path = os.path.realpath(os.path.join(bin_dir, lib))
            site.addsitedir(path)
        sys.path[:] = sys.path[prev_length:] + sys.path[0:prev_length]
        sys.real_prefix = sys.prefix
        sys.prefix = venv_dir
        self.python = os.path.join(venv_dir, "bin", "python3")
        self.verbose = verbose
        self._install_requirements(requires)

    def _install_requirements(self, requires):
        import subprocess
        subprocess.run(
            [self.python, '-m', 'pip', 'install', '-r', '/dev/stdin'],
            universal_newlines=True, input='\n'.join(requires)
        )

    def _install_mod(self, exc):
        import subprocess
        m = str(exc).split("'")[-2]
        if self.verbose > 0:
            print("Installing", m)
        subprocess.check_call(
            [self.python, '-m', 'pip', 'install', m],
            close_fds=(self.verbose < 2)
        )

    def __enter__(self):
        return self._install_mod

    def __exit__(self, exc_type, exc_value, exc_traceback):
        pass

with Venv("venv") as installer:
    while True:
        try:
            from flask import Flask, request, jsonify
            from datetime import datetime
            from clickhouse_driver import Client
            break
        except ModuleNotFoundError as e:
            installer(e)
Hack GPON