misc: add ImportFromPath, Path: add dir handling in remove

This commit is contained in:
Izalia Mae 2021-05-26 00:35:23 -04:00
parent c8d927abb3
commit a1f7b8942c

View file

@ -4,8 +4,9 @@ import hashlib, random, string, sys, os, json, socket, time
from os import environ as env from os import environ as env
from datetime import datetime from datetime import datetime
from getpass import getpass from getpass import getpass
from importlib import util
from pathlib import Path as Pathlib from pathlib import Path as Pathlib
from shutil import copyfile from shutil import copyfile, rmtree
from . import logging from . import logging
@ -105,6 +106,17 @@ def GetIp():
return ip 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): def Input(prompt, default=None, valtype=str, options=[], password=False):
input_func = getpass if password else input input_func = getpass if password else input
@ -264,10 +276,6 @@ class DotDict(dict):
return (k, v) return (k, v)
def update(self, data):
super().update(data)
def get(self, key, default=None): def get(self, key, default=None):
value = dict.get(self, key, default) value = dict.get(self, key, default)
return DotDict(value) if type(value) == dict else value return DotDict(value) if type(value) == dict else value
@ -562,10 +570,9 @@ class Path(object):
self.json.update(data) self.json.update(data)
# This needs to be extended to handle dirs with files/sub-dirs
def delete(self): def delete(self):
if self.isdir(): if self.isdir():
self.__path.rmdir() rmtree(self.__path)
else: else:
self.__path.unlink() self.__path.unlink()
@ -587,7 +594,7 @@ class Path(object):
class JsonEncoder(json.JSONEncoder): class JsonEncoder(json.JSONEncoder):
def default(self, obj): 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 str(obj)
return json.JSONEncoder.default(self, obj) return json.JSONEncoder.default(self, obj)