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.

1
  • Do you understand why the example gets a int value? The role of the type parameter? Commented Jul 9, 2018 at 15:35

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.