Initial commit
This commit is contained in:
71
utils.py
Normal file
71
utils.py
Normal file
@@ -0,0 +1,71 @@
|
||||
''' Utilities '''
|
||||
|
||||
import os
|
||||
import time
|
||||
import glob
|
||||
import shutil
|
||||
import hashlib
|
||||
import mimetypes
|
||||
import traceback
|
||||
|
||||
def pex() -> None:
|
||||
''' Print last exception '''
|
||||
traceback.print_exc()
|
||||
|
||||
def ensure_dir(path: str) -> bool:
|
||||
''' Ensure directory existance.
|
||||
'path' must NOT have trailing slash!
|
||||
'''
|
||||
try:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
return True
|
||||
except:
|
||||
return False
|
||||
|
||||
def get_script_dir() -> str:
|
||||
''' Returns path of this script (utils.py) '''
|
||||
return os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
def get_all_mods() -> list[str]:
|
||||
''' Get list of all supported mods '''
|
||||
sd = get_script_dir()
|
||||
res = [f for f in os.listdir(sd) if os.path.isfile(os.path.join(sd, f))]
|
||||
res = [f.split('.')[0] for f in res if f.startswith('mod_') and f.endswith('.py')]
|
||||
return res
|
||||
|
||||
def get_md5(data: str) -> str:
|
||||
''' Returns MD5 for data '''
|
||||
md5_hash = hashlib.md5()
|
||||
md5_hash.update(str(data).encode('ascii'))
|
||||
return md5_hash.hexdigest()
|
||||
|
||||
|
||||
def get_unique_md5() -> str:
|
||||
''' Returns unique MD5 '''
|
||||
md5_hash = hashlib.md5()
|
||||
md5_hash.update(str(time.time()).encode('ascii'))
|
||||
return md5_hash.hexdigest()
|
||||
|
||||
def which(cmd: str) -> str:
|
||||
''' Analogue to UNIX which '''
|
||||
return shutil.which(cmd)
|
||||
|
||||
def get_mime(ext) -> str:
|
||||
''' ext must not start with dot '''
|
||||
try:
|
||||
mime_type, _ = mimetypes.guess_type('file.%s' % ext)
|
||||
return mime_type
|
||||
except:
|
||||
return 'video/%s' % ext
|
||||
|
||||
def rm_glob(path_glob: str) -> None:
|
||||
''' Delete files using glob (files only) '''
|
||||
try:
|
||||
files = glob.glob(path_glob)
|
||||
for f in files:
|
||||
try:
|
||||
os.remove(f)
|
||||
except:
|
||||
pass
|
||||
except:
|
||||
pass
|
||||
Reference in New Issue
Block a user