92
92
import warnings
93
93
94
94
from gettext import gettext as _ , ngettext
95
+ from typing import Optional as _Optional
95
96
96
97
SUPPRESS = '==SUPPRESS=='
97
98
@@ -1896,14 +1897,7 @@ def parse_known_args(self, args=None, namespace=None):
1896
1897
if not hasattr (namespace , dest ):
1897
1898
setattr (namespace , dest , self ._defaults [dest ])
1898
1899
1899
- # parse the arguments and exit if there are any errors
1900
- if self .exit_on_error :
1901
- try :
1902
- namespace , args = self ._parse_known_args (args , namespace )
1903
- except ArgumentError as err :
1904
- self .error (str (err ))
1905
- else :
1906
- namespace , args = self ._parse_known_args (args , namespace )
1900
+ namespace , args = self ._parse_known_args (args , namespace )
1907
1901
1908
1902
if hasattr (namespace , _UNRECOGNIZED_ARGS_ATTR ):
1909
1903
args .extend (getattr (namespace , _UNRECOGNIZED_ARGS_ATTR ))
@@ -1970,7 +1964,7 @@ def take_action(action, argument_strings, option_string=None):
1970
1964
if conflict_action in seen_non_default_actions :
1971
1965
msg = _ ('not allowed with argument %s' )
1972
1966
action_name = _get_action_name (conflict_action )
1973
- raise ArgumentError ( action , msg % action_name )
1967
+ self . error ( msg % action_name , action = action )
1974
1968
1975
1969
# take the action if we didn't receive a SUPPRESS value
1976
1970
# (e.g. from a default)
@@ -2019,7 +2013,7 @@ def consume_optional(start_index):
2019
2013
explicit_arg = new_explicit_arg
2020
2014
else :
2021
2015
msg = _ ('ignored explicit argument %r' )
2022
- raise ArgumentError ( action , msg % explicit_arg )
2016
+ self . error ( msg % explicit_arg , action = action )
2023
2017
2024
2018
# if the action expect exactly one argument, we've
2025
2019
# successfully matched the option; exit the loop
@@ -2033,7 +2027,7 @@ def consume_optional(start_index):
2033
2027
# explicit argument
2034
2028
else :
2035
2029
msg = _ ('ignored explicit argument %r' )
2036
- raise ArgumentError ( action , msg % explicit_arg )
2030
+ self . error ( msg % explicit_arg , action = action )
2037
2031
2038
2032
# if there is no explicit argument, try to match the
2039
2033
# optional's string arguments with the following strings
@@ -2207,7 +2201,7 @@ def _match_argument(self, action, arg_strings_pattern):
2207
2201
msg = ngettext ('expected %s argument' ,
2208
2202
'expected %s arguments' ,
2209
2203
action .nargs ) % action .nargs
2210
- raise ArgumentError ( action , msg )
2204
+ self . error ( msg , action = action )
2211
2205
2212
2206
# return the number of arguments matched
2213
2207
return len (match .group (1 ))
@@ -2526,7 +2520,7 @@ def _get_value(self, action, arg_string):
2526
2520
type_func = self ._registry_get ('type' , action .type , action .type )
2527
2521
if not callable (type_func ):
2528
2522
msg = _ ('%r is not callable' )
2529
- raise ArgumentError ( action , msg % type_func )
2523
+ self . error ( msg % type_func , action = action )
2530
2524
2531
2525
# convert the value to the appropriate type
2532
2526
try :
@@ -2535,14 +2529,14 @@ def _get_value(self, action, arg_string):
2535
2529
# ArgumentTypeErrors indicate errors
2536
2530
except ArgumentTypeError as err :
2537
2531
msg = str (err )
2538
- raise ArgumentError ( action , msg )
2532
+ self . error ( msg , action = action )
2539
2533
2540
2534
# TypeErrors or ValueErrors also indicate errors
2541
2535
except (TypeError , ValueError ):
2542
2536
name = getattr (action .type , '__name__' , repr (action .type ))
2543
2537
args = {'type' : name , 'value' : arg_string }
2544
2538
msg = _ ('invalid %(type)s value: %(value)r' )
2545
- raise ArgumentError ( action , msg % args )
2539
+ self . error ( msg % args , action = action )
2546
2540
2547
2541
# return the converted value
2548
2542
return result
@@ -2553,7 +2547,7 @@ def _check_value(self, action, value):
2553
2547
args = {'value' : value ,
2554
2548
'choices' : ', ' .join (map (repr , action .choices ))}
2555
2549
msg = _ ('invalid choice: %(value)r (choose from %(choices)s)' )
2556
- raise ArgumentError ( action , msg % args )
2550
+ self . error ( msg % args , action = action )
2557
2551
2558
2552
# =======================
2559
2553
# Help-formatting methods
@@ -2617,15 +2611,18 @@ def exit(self, status=0, message=None):
2617
2611
self ._print_message (message , _sys .stderr )
2618
2612
_sys .exit (status )
2619
2613
2620
- def error (self , message ):
2621
- """error(message: string)
2622
-
2623
- Prints a usage message incorporating the message to stderr and
2624
- exits.
2614
+ def error (self , message : str , action : _Optional [Action ] = None ):
2615
+ """Prints a usage message incorporating the message to stderr and
2616
+ exits or raises an ArgumentError if self.exit_on_error is False.
2625
2617
2626
2618
If you override this in a subclass, it should not return -- it
2627
2619
should either exit or raise an exception.
2628
2620
"""
2621
+ if not self .exit_on_error :
2622
+ raise ArgumentError (action , message )
2623
+
2629
2624
self .print_usage (_sys .stderr )
2625
+ # If action is not None, custom formatting will be applied by ArgumentError
2626
+ message = str (ArgumentError (action , message ))
2630
2627
args = {'prog' : self .prog , 'message' : message }
2631
2628
self .exit (2 , _ ('%(prog)s: error: %(message)s\n ' ) % args )
0 commit comments