Argparse optional value for argument

I want to distinguish between these three cases:

  • The flag is generally missing python example.py ;
  • A flag is present, but without a python example.py -t value python example.py -t ; and
  • The flag is present and has a python example.py -t ~/some/path value of python example.py -t ~/some/path .

How to do this with Python argparse ? The first two cases will be considered action='store_true' , but then the third case will become invalid.

+8
source share
1 answer

You can do this with nargs='?' :

One argument will be used from the command line, if possible, and produced as a unit. If the command line argument is missing, the default value will be returned. Note that for optional arguments, there is an additional case - an option line is present, but not followed by a command line argument. In this case, the value from const will be produced.

Your three cases would give:

  1. Value default ;
  2. Value const ; and
  3. '~/some/path'

respectively. For example, the following simple implementation is provided:

 from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('-t', nargs='?', default='not present', const='present without value') print(parser.parse_args().t) 

You will get this output:

 $ python test.py not present $ python test.py -t present without value $ python test.py -t 'passed a value' passed a value 
+8
source

All Articles