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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With