From a1f7b8942cffe61ba749d6f53b605e222fa8307a Mon Sep 17 00:00:00 2001 From: Izalia Mae Date: Wed, 26 May 2021 00:35:23 -0400 Subject: [PATCH] misc: add ImportFromPath, Path: add dir handling in remove --- IzzyLib/misc.py | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/IzzyLib/misc.py b/IzzyLib/misc.py index 4d52071..c966e99 100644 --- a/IzzyLib/misc.py +++ b/IzzyLib/misc.py @@ -4,8 +4,9 @@ import hashlib, random, string, sys, os, json, socket, time from os import environ as env from datetime import datetime from getpass import getpass +from importlib import util from pathlib import Path as Pathlib -from shutil import copyfile +from shutil import copyfile, rmtree from . import logging @@ -105,6 +106,17 @@ def GetIp(): return ip +def ImportFromPath(mod_path): + mod_path = Path(mod_path) + path = mod_path.join('__init__.py') if mod_path.isdir() else mod_path + name = path.name.replace('.py', '', -1) + + spec = util.spec_from_file_location(name, path.str()) + module = util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + def Input(prompt, default=None, valtype=str, options=[], password=False): input_func = getpass if password else input @@ -264,10 +276,6 @@ class DotDict(dict): return (k, v) - def update(self, data): - super().update(data) - - def get(self, key, default=None): value = dict.get(self, key, default) return DotDict(value) if type(value) == dict else value @@ -562,10 +570,9 @@ class Path(object): self.json.update(data) - # This needs to be extended to handle dirs with files/sub-dirs def delete(self): if self.isdir(): - self.__path.rmdir() + rmtree(self.__path) else: self.__path.unlink() @@ -587,7 +594,7 @@ class Path(object): class JsonEncoder(json.JSONEncoder): def default(self, obj): - if type(obj) not in [str, int, float, dict]: + if not any(map(isinstance, [obj], [str, int, float, dict])): return str(obj) return json.JSONEncoder.default(self, obj)