Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python argparse default string value

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.

like image 558
macro_controller Avatar asked Dec 06 '22 11:12

macro_controller


1 Answers

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.

like image 72
tzaman Avatar answered Dec 31 '22 11:12

tzaman