9

using argparse:

parser.add_argument("-o", "--output", help="Log to file")

I want to achieve the following behavior:

  1. The user doesn't specify the -o flag - no logging should be done.
  2. User specifies the -o with nothing - I should log to a default location, defined within my program.
  3. User specifies -o and a string(path) - I should log there.

Does anyone know the best way to use add_argument to achieve that? I saw a similar example with int values, but in my case, it doesn't get my default value.

macro_controller
  • 1,469
  • 1
  • 14
  • 32

1 Answers1

19

You can use nargs='?' for this:

parser.add_argument('-o', '--output', 
                    nargs='?', default=None, const='my_default_location')

If not present, it will produce the default value, if present but without a value it'll use const, otherwise it'll use the supplied value.

Also read through the other examples in the docs, there's a sample for an optional output file which could be useful.

tzaman
  • 46,925
  • 11
  • 90
  • 115