-3

I have a script that has a argument which has a default value. I want to do something:

$sample.py => Dont do anything
$sample.py -R => Use default value of -R
$sample.py -R <value> =>do something based on value passed

Is this doable in argparse?

Hi all. Please note that my problem is different from the one mentioned in the solution.

Basically i want action corresponding to -R to be performed only when i pass -R on command line. If only -R is passed then value of -R is default value.

If i run the py file without -R then no action corresponding to -R should be done.

Amit Goel
  • 35
  • 1
  • 10

1 Answers1

3
parser.add_argument('-R',nargs='?', default='default',const='const')

should produce

test.py => namspace(R='default')
test.py -R => namespace(R='const')
test.py -R value => namespace(R='value')

This is documented in https://docs.python.org/3/library/argparse.html#nargs, subsection nargs='?'.

hpaulj
  • 221,503
  • 14
  • 230
  • 353