1
+ # -*- encoding: utf-8 -*-
2
+ """Modulo common.get_input_params
3
+
4
+ Contém a classe responsável por ler os valores dos parâmetros de entrada da linha de comando.
5
+
6
+ Autor: Rogers Reiche de Mendonça <rogers.rj@gmail.com>
7
+ Data: Setembro/2020
8
+ """
9
+ import getopt
10
+
11
+ from typing import Dict , NoReturn
12
+
13
+ from . import util
14
+ from .input_param import InputParamDef
15
+
16
+ InputParamDefDictType = Dict [str , InputParamDef ]
17
+
18
+ class GetInputParams :
19
+ def __init__ (self , spec_name : str , input_param_def_dict : InputParamDefDictType , argv : list ):
20
+ """Construtor da classe GetInputParams.
21
+
22
+ :param spec_name str: Spec module name (__spec__.name)
23
+ :param input_param_def_dict InputParamDefDictType: Dicionário de definição dos parâmetros a ser lidos da linha de comando.
24
+ :param argv list: Arguments list (sys.argv)
25
+ """
26
+ if (not isinstance (argv , list )):
27
+ raise ValueError (f"argv (type = { type (argv )} ) must be a list object." )
28
+ elif (not isinstance (input_param_def_dict , dict )):
29
+ raise ValueError (f"input_param_def_dict (type = { type (input_param_def_dict )} ) must be a dict object." )
30
+ else :
31
+ self .spec_name = util .strip_val (spec_name ).replace (".__main__" , "" )
32
+ self .input_param_def_dict = input_param_def_dict
33
+ self .script_file = util .strip_val (argv [0 ])
34
+ self .args = [util .strip_val (v ) for v in argv [1 :]]
35
+
36
+ def _get_longopts (self ) -> list :
37
+ longopts = [k + '=' for k in self .input_param_def_dict ]
38
+ longopts .append ('help' )
39
+ return longopts
40
+
41
+ def _read_input (self ) -> dict :
42
+ opts , args = getopt .getopt (self .args , '' , self ._get_longopts ())
43
+ return {p [2 :]:v for p , v in opts }
44
+
45
+ def _get_mandatory_params (self ) -> list :
46
+ return [k for k , v in self .input_param_def_dict .items () if not v .default ]
47
+
48
+ def _check_mandatory_params (self , input_params : dict ) -> NoReturn :
49
+ mandatory_params = self ._get_mandatory_params ()
50
+ for param in self ._get_mandatory_params ():
51
+ if param not in input_params :
52
+ raise getopt .GetoptError ('Parametros obrigatorios: ' + ', ' .join (mandatory_params ))
53
+
54
+ def _complement_default_values (self , input_params : dict ) -> dict :
55
+ for k in self .input_param_def_dict :
56
+ if not input_params .get (k ):
57
+ input_params [k ] = self .input_param_def_dict [k ].default
58
+ return input_params
59
+
60
+ def get (self ) -> dict :
61
+ """Obtém os valores dos parametros de entrada da linha de comando.
62
+ """
63
+ try :
64
+ input_params = self ._read_input ()
65
+
66
+ self ._check_mandatory_params (input_params )
67
+
68
+ return self ._complement_default_values (input_params )
69
+
70
+ except getopt .GetoptError as e :
71
+ self .help ()
72
+ raise e
73
+
74
+ def help (self ) -> NoReturn :
75
+ """Imprime a ajuda da linha de comando de execução.
76
+ """
77
+ module_exec = f"python -m { self .spec_name } "
78
+
79
+ param_usage = ''
80
+ param_defs = ''
81
+ param_example = ''
82
+ for k , param in self .input_param_def_dict .items ():
83
+ param_usage += f"--{ param .name } =<valor> "
84
+
85
+ if (param .default ):
86
+ param_defs += f". { param .name } = { param .definition } (Default: { param .default } )\r \n "
87
+ else :
88
+ param_defs += f". { param .name } = { param .definition } \r \n "
89
+
90
+ param_example += f"--{ param .name } ={ param .example } "
91
+
92
+ print (f"* Uso:\r \n { module_exec } { param_usage } \r \n " )
93
+ print (f"* Parametros:\r \n { param_defs } " )
94
+ print (f"* Exemplo:\r \n { module_exec } { param_example } \r \n " )
0 commit comments