@@ -201,7 +201,18 @@ def _run(self):
201201 # reconstruct the cmd2 command from the python call
202202 cmd_str = ['' ]
203203
204- def process_flag (action , value ):
204+ def has_optional_prefix (arg : str ) -> bool :
205+ """
206+ Checks if an argument value begins with prefix characters intended for argparse optional values
207+ :param arg: argument value being checked
208+ :return: True if arg begins with one of the prefix characters
209+ """
210+ for char in self ._parser .prefix_chars :
211+ if arg .startswith (char ):
212+ return True
213+ return False
214+
215+ def process_argument (action , value ):
205216 if isinstance (action , argparse ._CountAction ):
206217 if isinstance (value , int ):
207218 for _ in range (value ):
@@ -221,10 +232,16 @@ def process_flag(action, value):
221232 # was the argument a flag?
222233 if action .option_strings :
223234 cmd_str [0 ] += '{} ' .format (action .option_strings [0 ])
235+ is_flag = True
236+ else :
237+ is_flag = False
224238
225239 if isinstance (value , List ) or isinstance (value , tuple ):
226240 for item in value :
227241 item = str (item ).strip ()
242+ if not is_flag and has_optional_prefix (item ):
243+ raise ValueError ('Value provided for {} ({}) appears to be an optional' .
244+ format (action .dest , item ))
228245 item = quote_string_if_needed (item )
229246 cmd_str [0 ] += '{} ' .format (item )
230247
@@ -237,6 +254,8 @@ def process_flag(action, value):
237254
238255 else :
239256 value = str (value ).strip ()
257+ if not is_flag and has_optional_prefix (value ):
258+ raise ValueError ('Value provided for {} ({}) appears to be an optional' .format (action .dest , value ))
240259 value = quote_string_if_needed (value )
241260 cmd_str [0 ] += '{} ' .format (value )
242261
@@ -254,11 +273,11 @@ def process_action(action):
254273 elif isinstance (action , argparse ._AppendAction ):
255274 if isinstance (self ._args [action .dest ], list ) or isinstance (self ._args [action .dest ], tuple ):
256275 for values in self ._args [action .dest ]:
257- process_flag (action , values )
276+ process_argument (action , values )
258277 else :
259- process_flag (action , self ._args [action .dest ])
278+ process_argument (action , self ._args [action .dest ])
260279 else :
261- process_flag (action , self ._args [action .dest ])
280+ process_argument (action , self ._args [action .dest ])
262281
263282 def traverse_parser (parser ):
264283 # first process optional flag arguments
0 commit comments