Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zero or one argument [duplicate]

Which action I have to use, when parameter can be with zero or one argument? I have to run code like this and will be set default value 4 (this variant exit with error)

--pretty-xml
error: argument --pretty-xml: expected one argument

but alse I can run code like this

--pretty-xml = 2 

my code looks like this

parameter.add_argument('--pretty-xml',  dest="pretty", action="append", default=[4])

What needs to be changed to work for both options parameters ? Thanks

like image 619
Bando Avatar asked Jan 04 '23 05:01

Bando


1 Answers

You need to use nargs argument with ? and the default and const parameters:

'?'. One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from default will be produced. ...


parser.add_argument('--pretty-xml', dest='pretty', default=4, const=5, nargs='?', type=int)

This will have the value n if called like --pretty-xml=n, or 5 if called like --pretty-xml or 4 if --pretty-xml isn't present on the command line at all.

NOTE: used type=int to check type and convert to int type. Otherwise returns string if the argument is specified, returns int 4 if no argument is specified.

like image 196
falsetru Avatar answered Jan 17 '23 01:01

falsetru