39
39
parent_parsers ,
40
40
previous_config ,
41
41
)
42
+ from .deprecated import ParserDeprecations
42
43
from .formatters import DefaultHelpFormatter , empty_help , get_env_var
43
44
from .jsonnet import ActionJsonnet , ActionJsonnetExtVars
44
45
from .jsonschema import ActionJsonSchema
74
75
from .typehints import ActionTypeHint , is_subclass_spec
75
76
from .typing import is_final_class
76
77
from .util import (
77
- ParserError ,
78
78
Path ,
79
+ argument_error ,
79
80
change_to_path_dir ,
80
81
get_private_kwargs ,
81
82
identity ,
82
83
is_subclass ,
83
84
return_parser_if_captured ,
84
- usage_and_exit_error_handler ,
85
85
)
86
86
87
87
__all__ = ['ActionsContainer' , 'ArgumentParser' ]
@@ -183,7 +183,7 @@ class _ArgumentGroup(ActionsContainer, argparse._ArgumentGroup):
183
183
parser : Optional ['ArgumentParser' ] = None
184
184
185
185
186
- class ArgumentParser (ActionsContainer , ArgumentLinking , argparse .ArgumentParser ):
186
+ class ArgumentParser (ParserDeprecations , ActionsContainer , ArgumentLinking , argparse .ArgumentParser ):
187
187
"""Parser for command line, yaml/jsonnet files and environment variables."""
188
188
189
189
formatter_class : Type [DefaultHelpFormatter ]
@@ -195,8 +195,8 @@ def __init__(
195
195
self ,
196
196
* args ,
197
197
env_prefix : Union [bool , str ] = True ,
198
- error_handler : Optional [Callable [['ArgumentParser' , str ], None ]] = usage_and_exit_error_handler ,
199
198
formatter_class : Type [DefaultHelpFormatter ] = DefaultHelpFormatter ,
199
+ exit_on_error : bool = True ,
200
200
logger : Union [bool , str , dict , logging .Logger ] = False ,
201
201
version : Optional [str ] = None ,
202
202
print_config : Optional [str ] = '--print_config' ,
@@ -215,7 +215,6 @@ def __init__(
215
215
216
216
Args:
217
217
env_prefix: Prefix for environment variables. ``True`` to derive from ``prog``.
218
- error_handler: Handler for parsing errors, if None raises :class:`.ParserError` exception.
219
218
formatter_class: Class for printing help messages.
220
219
logger: Configures the logger, see :class:`.LoggerProperty`.
221
220
version: Program version which will be printed by the --version argument.
@@ -229,6 +228,7 @@ def __init__(
229
228
super ().__init__ (* args , formatter_class = formatter_class , logger = logger , ** kwargs )
230
229
if self .groups is None :
231
230
self .groups = {}
231
+ self .exit_on_error = exit_on_error
232
232
self .required_args : Set [str ] = set ()
233
233
self .save_path_content : Set [str ] = set ()
234
234
self .default_config_files = default_config_files # type: ignore
@@ -237,7 +237,6 @@ def __init__(
237
237
self .env_prefix = env_prefix
238
238
self .parser_mode = parser_mode
239
239
self .dump_header = dump_header
240
- self .error_handler = error_handler
241
240
self ._print_config = print_config
242
241
if version is not None :
243
242
self .add_argument ('--version' , action = 'version' , version = '%(prog)s ' + version , help = 'Print version and exit.' )
@@ -257,7 +256,7 @@ def parse_known_args(self, args=None, namespace=None):
257
256
try :
258
257
with patch_namespace (), parser_context (parent_parser = self , lenient_check = True ), ActionTypeHint .subclass_arg_context (self ):
259
258
namespace , args = self ._parse_known_args (args , namespace )
260
- except ( argparse .ArgumentError , ParserError ) as ex :
259
+ except argparse .ArgumentError as ex :
261
260
self .error (str (ex ), ex )
262
261
263
262
return namespace , args
@@ -367,7 +366,7 @@ def parse_args( # type: ignore[override]
367
366
A config object with all parsed values.
368
367
369
368
Raises:
370
- ParserError : If there is a parsing error and error_handler=None .
369
+ ArgumentError : If the parsing fails error and exit_on_error=True .
371
370
"""
372
371
skip_check = get_private_kwargs (kwargs , _skip_check = False )
373
372
return_parser_if_captured (self )
@@ -427,7 +426,7 @@ def parse_object(
427
426
A config object with all parsed values.
428
427
429
428
Raises:
430
- ParserError : If there is a parsing error and error_handler=None .
429
+ ArgumentError : If the parsing fails error and exit_on_error=True .
431
430
"""
432
431
skip_check , skip_required = get_private_kwargs (kwargs , _skip_check = False , _skip_required = False )
433
432
@@ -506,7 +505,7 @@ def parse_env(
506
505
A config object with all parsed values.
507
506
508
507
Raises:
509
- ParserError : If there is a parsing error and error_handler=None .
508
+ ArgumentError : If the parsing fails error and exit_on_error=True .
510
509
"""
511
510
skip_check , skip_subcommands = get_private_kwargs (kwargs , _skip_check = False , _skip_subcommands = False )
512
511
@@ -551,7 +550,7 @@ def parse_path(
551
550
A config object with all parsed values.
552
551
553
552
Raises:
554
- ParserError : If there is a parsing error and error_handler=None .
553
+ ArgumentError : If the parsing fails error and exit_on_error=True .
555
554
"""
556
555
fpath = Path (cfg_path , mode = get_config_read_mode ())
557
556
with change_to_path_dir (fpath ):
@@ -594,7 +593,7 @@ def parse_string(
594
593
A config object with all parsed values.
595
594
596
595
Raises:
597
- ParserError : If there is a parsing error and error_handler=None .
596
+ ArgumentError : If the parsing fails error and exit_on_error=True .
598
597
"""
599
598
skip_check , fail_no_subcommand = get_private_kwargs (kwargs , _skip_check = False , _fail_no_subcommand = True )
600
599
@@ -981,8 +980,8 @@ def get_defaults(self, skip_check: bool = False) -> Namespace:
981
980
skip_check = skip_check ,
982
981
skip_required = True ,
983
982
)
984
- except (TypeError , KeyError , ParserError ) as ex :
985
- raise ParserError (f'Problem in default config file "{ default_config_file } " : : { ex .args [0 ]} ' ) from ex
983
+ except (TypeError , KeyError , argparse . ArgumentError ) as ex :
984
+ raise argument_error (f'Problem in default config file "{ default_config_file } ": { ex .args [0 ]} ' ) from ex
986
985
meta = cfg .get ('__default_config__' )
987
986
if isinstance (meta , list ):
988
987
meta .append (default_config_file )
@@ -1000,14 +999,19 @@ def get_defaults(self, skip_check: bool = False) -> Namespace:
1000
999
## Other methods ##
1001
1000
1002
1001
def error (self , message : str , ex : Optional [Exception ] = None ) -> NoReturn :
1003
- """Logs error message if a logger is set, calls the error handler and raises a ParserError ."""
1002
+ """Logs error message if a logger is set and exits or raises an ArgumentError ."""
1004
1003
self ._logger .error (message )
1005
- if self ._error_handler is not None :
1004
+ if callable ( self ._error_handler ) :
1006
1005
self ._error_handler (self , message )
1007
- if ex is None :
1008
- raise ParserError (message )
1009
- else :
1010
- raise ParserError (message ) from ex
1006
+ if not self .exit_on_error :
1007
+ raise argument_error (message ) from ex
1008
+ elif 'JSONARGPARSE_DEBUG' in os .environ :
1009
+ self ._logger .debug ('Debug enabled, thus raising exception instead of exit.' )
1010
+ raise argument_error (message ) from ex
1011
+ self .print_usage (sys .stderr )
1012
+ args = {'prog' : self .prog , 'message' : message }
1013
+ sys .stderr .write ('%(prog)s: error: %(message)s\n ' % args )
1014
+ self .exit (2 )
1011
1015
1012
1016
1013
1017
def check_config (
@@ -1193,7 +1197,7 @@ def format_help(self) -> str:
1193
1197
if isinstance (config_files , list ):
1194
1198
config_files = [str (x ) for x in config_files ]
1195
1199
note = f'default values below are the ones overridden by the contents of: { config_files } '
1196
- except ParserError as ex :
1200
+ except argparse . ArgumentError as ex :
1197
1201
note = f'tried getting defaults considering default_config_files but failed due to: { ex } '
1198
1202
group = self ._default_config_files_group
1199
1203
group .description = f'{ self ._default_config_files } , Note: { note } '
@@ -1327,27 +1331,6 @@ def _check_value_key(self, action: argparse.Action, value: Any, key: str, cfg: O
1327
1331
1328
1332
## Properties ##
1329
1333
1330
- @property
1331
- def error_handler (self ) -> Optional [Callable [['ArgumentParser' , str ], None ]]:
1332
- """Property for the error_handler function that is called when there are parsing errors.
1333
-
1334
- :getter: Returns the current error_handler function.
1335
- :setter: Sets a new error_handler function (Callable[self, message:str] or None).
1336
-
1337
- Raises:
1338
- ValueError: If an invalid value is given.
1339
- """
1340
- return self ._error_handler
1341
-
1342
-
1343
- @error_handler .setter
1344
- def error_handler (self , error_handler : Optional [Callable [['ArgumentParser' , str ], None ]]):
1345
- if callable (error_handler ) or error_handler is None :
1346
- self ._error_handler = error_handler
1347
- else :
1348
- raise ValueError ('error_handler can be either a Callable or None.' )
1349
-
1350
-
1351
1334
@property
1352
1335
def default_config_files (self ) -> List [str ]:
1353
1336
"""Default config file locations.
0 commit comments