Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python argparse - optional argument to be none or more

I have an optional argument -s to setup the tool. I hope user could give an input or use the default value. If he decides to use the default one, he should be able to skip giving extra input.

for example, myScript -s and myScript -s "Hello" should both work

Seems action = store_true not working well with nargs='*'

like image 672
Jieke Wei Avatar asked Dec 07 '25 20:12

Jieke Wei


1 Answers

argparse store action allows the programmer to differentiate 3 use cases:

  • option is not present (uses default)
  • option is present and has no additional value (uses const)
  • option is present and has a value (uses the passed value)

Assuming that you want -s and -s Hello to perform the same, you could use

parser = argparse.ArgumentParser(description = "Some desc.")
parser.add_argument("-s", nargs='?', const='Hello', default = None)

then you can test it:

>>> parser.parse_args([])
Namespace(s=None)
>>> parser.parse_args(["-s"])
Namespace(s='Hello')
>>> parser.parse_args(["-s", 'Hello'])
Namespace(s='Hello')
>>> parser.parse_args(["-s", 'foo'])
Namespace(s='foo')
like image 98
Serge Ballesta Avatar answered Dec 10 '25 10:12

Serge Ballesta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!