helpers.py

1.5 kB · python · 60 lines

1import logging2import random3import sys45# LOGGING67_logging_configured = False89def create_logger(name: str) -> logging.Logger:10    global _logging_configured11    if not _logging_configured:12        logging.basicConfig(level=logging.INFO, format="(%(name)s) %(message)s")13        _logging_configured = True14    return logging.getLogger(name)1516# APP1718class App:19    def __init__(self, name: str):20        self.name = name21        self.commands = {}22        self.playground_fn = None2324    def add(self, name: str, fn, description: str, nargs: int = 0):25        self.commands[name] = (fn, description, nargs)2627    def test(self, fn):28        self.playground_fn = fn2930    def help(self):31        print(self.name)32        for name, (_, desc, _) in self.commands.items():33            print(f"{name:<16}{desc}")3435    def run(self):36        create_logger(self.name)37        args = sys.argv[1:]38        if not args:39            if self.playground_fn:40                self.playground_fn()41            else:42                self.help()43            return44        command = args[0]45        if command in self.commands:46            fn, _, nargs = self.commands[command]47            if nargs and args[1:]:48                fn(*[int(a) if a.isdigit() else a for a in args[1:nargs+1]])49            else:50                fn()51        else:52            self.help()5354# UTILS5556def hex_key(k: int = 8) -> str:57    return "".join(random.choices("0123456789abcdef", k=k))5859def random_seed() -> int:60    return random.randint(0, 2**32 - 1)