44
55from .log_level import str_to_level
66from .prof import profile
7+ '''
8+ >>> from byexample.cmdline import ByexampleArgumentParser
9+ '''
710
811
912class _CSV (argparse .Action ):
@@ -181,6 +184,74 @@ def _expand_glob_patterns(gpatterns):
181184 return list (set (fnames ))
182185
183186
187+ class ByexampleArgumentParser (argparse .ArgumentParser ):
188+ def convert_arg_line_to_args (self , arg_line ):
189+ ''' Return a list with the arguments read from a line.
190+
191+ If in the line there is a flag/argument with one or more
192+ values the flag may be separated from its value(s) with
193+ a space and this method will replace it with an '='.
194+
195+ This is in order to produce a single argument for each
196+ line as it is expected by argparse.ArgumentParser.
197+
198+ >>> parser = ByexampleArgumentParser()
199+ >>> parser.convert_arg_line_to_args('--skip=foo')
200+ ['--skip=foo']
201+
202+ >>> parser.convert_arg_line_to_args('--skip foo')
203+ ['--skip=foo']
204+
205+ >>> parser.convert_arg_line_to_args('--skip=foo bar')
206+ ['--skip=foo bar']
207+
208+ >>> parser.convert_arg_line_to_args('--skip foo bar')
209+ ['--skip=foo bar']
210+
211+ >>> parser.convert_arg_line_to_args('--skip=')
212+ ['--skip=']
213+
214+ >>> parser.convert_arg_line_to_args('--skip ')
215+ ['--skip ']
216+
217+ >>> parser.convert_arg_line_to_args('--skip')
218+ ['--skip']
219+
220+ >>> parser.convert_arg_line_to_args('foo')
221+ ['foo']
222+
223+ >>> parser.convert_arg_line_to_args('foo bar')
224+ ['foo bar']
225+ '''
226+ arg_line = arg_line .lstrip ()
227+ if arg_line and arg_line [0 ] in self .prefix_chars :
228+ flag , _ , value = arg_line .partition (' ' )
229+ value = value .lstrip ()
230+ if not value :
231+ # the flag is argumentless or it is using '='
232+ # to paste the flag with its argument,
233+ # return the whole line then
234+ #
235+ # Ex:
236+ # -foo
237+ # -bar=32
238+ # -zaz=
239+ return [arg_line ]
240+ else :
241+ if '=' in flag :
242+ # the line already has the '=' to paste the
243+ # flag with the argument, leave them as they are
244+ #
245+ # Ex:
246+ # -bar=32 42
247+ return [arg_line ]
248+
249+ # Paste the flag with its value (or values) with a '='
250+ return [flag + '=' + value ]
251+
252+ return [arg_line ]
253+
254+
184255@profile
185256def parse_args (args = None ):
186257 '''Parse the arguments args and return the them.
@@ -192,7 +263,7 @@ def parse_args(args=None):
192263 )
193264
194265 python_version = sys .version .split (' ' , 1 )[0 ]
195- parser = argparse . ArgumentParser (
266+ parser = ByexampleArgumentParser (
196267 fromfile_prefix_chars = '@' ,
197268 add_help = False ,
198269 formatter_class = HelpExtraFormatter ,
0 commit comments