izzylib/IzzyLib/misc.py

137 lines
3.2 KiB
Python

'''Miscellaneous functions'''
import random, string, sys, os, shlex, subprocess, socket, traceback
from os.path import abspath, dirname, basename, isdir, isfile
from os import environ as env
from datetime import datetime
from collections import namedtuple
from . import logging
def boolean(v, fail=True):
if type(v) in [dict, list, tuple]:
raise ValueError(f'Value is not a string, boolean, int, or nonetype: {value}')
'''make the value lowercase if it's a string'''
value = v.lower() if isinstance(v, str) else v
if value in [1, True, 'on', 'y', 'yes', 'true', 'enable']:
'''convert string to True'''
return True
elif value in [0, False, None, 'off', 'n', 'no', 'false', 'disable', '']:
'''convert string to False'''
return False
elif not fail:
'''just return the value'''
return value
else:
raise ValueError(f'Value cannot be converted to a boolean: {value}')
def randomgen(chars=20):
if not isinstance(chars, int):
raise TypeError(f'Character length must be an integer, not a {type(char)}')
return ''.join(random.choices(string.ascii_letters + string.digits, k=chars))
def formatUTC(timestamp=None, ap=False):
date = datetime.fromtimestamp(timestamp) if timestamp else datetime.utcnow()
if ap:
return date.strftime('%Y-%m-%dT%H:%M:%SZ')
return date.strftime('%a, %d %b %Y %H:%M:%S GMT')
def config_dir(modpath=None):
if env.get('CONFDIR'):
'''set the storage path to the environment variable if it exists'''
stor_path = abspath(env['CONFDIR'])
else:
stor_path = f'{os.getcwd()}'
if modpath and not env.get('CONFDIR'):
modname = basename(dirname(modpath))
if isdir(f'{stor_path}/{modname}'):
'''set the storage path to CWD/data if the module or script is in the working dir'''
stor_path += '/data'
if not isdir (stor_path):
os.makedirs(stor_path, exist_ok=True)
return stor_path
def getBin(filename):
for pathdir in env['PATH'].split(':'):
fullpath = os.path.join(pathdir, filename)
if os.path.isfile(fullpath):
return fullpath
raise FileNotFoundError(f'Cannot find {filename} in path.')
def Try(funct, *args, **kwargs):
Result = namedtuple('Result', 'result exception')
out = None
exc = None
try:
out = funct(*args, **kwargs)
except Exception as e:
traceback.print_exc()
exc = e
return Result(out, exc)
def sudo(cmd, password, user=None):
### Please don't pur your password in plain text in a script
### Use a module like 'getpass' to get the password instead
if isinstance(cmd, list):
cmd = ' '.join(cmd)
elif not isinstance(cmd, str):
raise ValueError('Command is not a list or string')
euser = os.environ.get('USER')
cmd = ' '.join(['sudo', '-u', user, cmd]) if user and euser != user else 'sudo ' + cmd
sudocmd = ' '.join(['echo', f'{password}', '|', cmd])
proc = subprocess.Popen(['/usr/bin/env', 'bash', '-c', sudocmd])
return proc
def getip():
# Get the main IP address of the machine
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(('10.255.255.255', 1))
data = s.getsockname()
ip = data[0]
except Exception:
ip = '127.0.0.1'
finally:
s.close()
return ip
def merp():
log = logging.getLogger('merp-heck', {'level': 'merp', 'date': False})
log.merp('heck')