Source code for corelibs.lazy
"""
>>>
.. module:: lazy.py
:platform: Unix, Windows
:synopsis: Module avec des fonctions, décorateurs, etc. utiles pour les grosses faignasses comme moi qui n'ont pas
envie de tout réécrire à chaque fois... =}
.. moduleauthor:: Michel TRUONG <michel.truong@gmail.com>
>>>
"""
import datetime as dt
import logging as log
import os
import pathlib
import sys
import coloredlogs as cl
import corelibs.config as config
# config pour utilisation interne de la log ---------------------------------------------------------------------------#
cl.DEFAULT_FIELD_STYLES = config.DEFAULT_FIELD_STYLES
cl.DEFAULT_LEVEL_STYLES = config.DEFAULT_LEVEL_STYLES
cl.DEFAULT_LOG_FORMAT = config.DEFAULT_LOG_FORMAT
cl.DEFAULT_DATE_FORMAT = config.DEFAULT_LOG_DATE_FORMAT
default_log_label = os.path.basename(__file__)
if config.DEFAULT_LOG_LABEL != "SHORT":
default_log_label = __file__
cl.install(
level=config.DEFAULT_LOG_LEVEL,
fmt=cl.DEFAULT_LOG_FORMAT
)
log = log.getLogger(default_log_label)
# config pour utilisation interne de la log /--------------------------------------------------------------------------#
[docs]def get_timestamp():
"""
Retourne un timestamp normalisé au format YYYYMMDD_HHMMSS.SSSSSS ; utile pour suffixer les noms des fichiers
.. todo::
blah blah
hé hé
:return:
timestamp
"""
date_time = str(dt.datetime.now()).split()
return "".join(date_time[0].split("-")) + "_" + "".join(date_time[1].split(":"))
[docs]def get_abspath(root_dir, dir_2_join):
"""
Retourne le chemin absolu normalisé à partir d'un répertoire racine et un dossier
:param root_dir:
répertoire racine (e.g. "C:\documents\dir")
:param dir_2_join:
dosssier à concaténer (e.g. "toto")
:return:
le chemin normalisé (e.g. "C:\documents\dir\toto")
"""
return os.path.abspath(os.path.join(root_dir, dir_2_join))
[docs]def get_basename(path):
"""
TODO:: retourner un couple basename + dirname
Retourne le basename à partir d'un chemin normalisé (e.g. "C:\documents\dir" retournera "dir")
:param path:
chemin normalisé
:return:
le basename du chemin normalisé donné en paramètre
"""
return os.path.basename(os.path.normpath(path))
[docs]def get_script_path():
"""
Retourne le chemin du script courant (ou celui dans l'interpréteur de commandes)
:return:
os.path.realpath(sys.argv[0])
ou
os.path.dirname(path)
"""
path = os.path.realpath(sys.argv[0])
if os.path.isdir(path):
return path
return os.path.dirname(path)
[docs]def mkdir(location=None, is_log=True):
"""
Créer un répertoire standard de manière récursive ; si le ou les parents n'existent pas, ils seront créés dans
la foulée.
Par défaut, lorsque `lazy.mkdir()` est appelé, 2 répertoires en plus sont créés :
* 1 pour recevoir les fichiers logs
* 1 pour recevoir les sorties
.. note::
Les noms respectifs des répertoires log et de sortie sont gérés par des constantes nommées :
* `config.DEFAULT_LOGS_DIR_NAME = "__LOGS__"`
* `config.DEFAULT_OUTPUT_DIR_NAME = "__OUTPUT__"`
Ces constantes peuvent être définies dans un fichier conf ou réécrasées dans le programme courant qui
appelle `lazy.mkdir()`
:param location:
la location du répertoire à créer.,
defaults to le chemin retourné par `lazy.get_script_path()`
:param is_log:
spécifie le type de répertoire à créer (standard ou un répertoire avec 2 sous répertoires LOG & OUTPUT).,
defaults to True
:return:
Rien...
"""
try:
if location is None:
default_output_dir_path = get_abspath(get_script_path(), config.DEFAULT_OUTPUT_DIR_NAME)
else:
default_output_dir_path = get_abspath(location, config.DEFAULT_OUTPUT_DIR_NAME)
if is_log:
dir_path = get_abspath(default_output_dir_path, config.DEFAULT_LOGS_DIR_NAME)
dir_2_make = config.DEFAULT_LOGS_DIR_NAME
else:
dir_path = location
dir_2_make = get_basename(location)
pathlib.Path(dir_path).mkdir(parents=True, exist_ok=False)
except FileExistsError:
log.warning("Le fichier existe déjà")
except FileNotFoundError:
log.warning("Fichier ou répertoire inexistant")
except PermissionError:
log.critical("Habilitations insuffisantes")
except OSError:
log.error("Le nom du fichier contient des caractères interdits")
else:
log.info("Le dossier {dir_2_make} a été correctement créé à l'emplacement {logs_path}"
.format(dir_2_make=dir_2_make, logs_path=dir_path)
)