ArgumentError dans argparse
L'utilisation d'ArgumentError dans la fonction d'argparse lève elle même une erreur. En effet, elle prend en premier argument un objet Action et pas une chaîne de caractère. Il faut plutôt utiliser ArgumentTypeError
De plus, je pense qu'il faut propager le message d'erreur et attraper en plus le TypeError, car sinon on perd l'info de l'erreur qui peut être pratique dans beaucoup de cas.
def check_conf_file(input_conf):
"""
Check if python conf file can be loaded and load it if possible.
Parameters
----------
input_conf : str
The path to the python configuration file
Returns
-------
module
The loaded module from the file.
Raises
------
argparse.ArgumentError
If the file cannot be read or if the module cannot be loaded.
"""
list_files = glob.glob(input_conf)
if len(list_files) != 1:
msg = "error: Configuration file {} cannot be found"
raise argparse.ArgumentError("conf", msg.format(input_conf))
# extract path
file_ = os.path.abspath(list_files[0])
module_path = os.path.dirname(file_)
module_name = os.path.splitext(os.path.basename(file_))[0]
# check if module path is in python path. if not add it
if module_path not in sys.path:
sys.path.append(module_path)
try:
conf = importlib.import_module(module_name)
except TypeError as e:
msg = f"error: something went wrong parsing the file {file_}"
msg += "\n" + str(e)
raise argparse.ArgumentTypeError(msg)
except ImportError as e:
msg = f"error: cannot import module {module_name}"
msg += "\n" + str(e)
raise argparse.ArgumentTypeError(msg)
return conf