1

I'm trying to implement the following behavior for the CLI for my Python script:

  • if the -o option is not present, the script does not write to a file
  • if the -o option is present without an argument, the script writes to a default filename
  • if the -o option is present with an argument, the script writes to a filename supplied by the user
$ python myscript.py               # does not write to file
$ python myscript.py -o            # writes to default.txt
$ python myscript.py -o myfile.txt # writes to myfile.txt

Is it possible to achieve this with argparse? Here's what I've tried when building my parser:

parser.add_argument('-o', '--output', action='store_true', type=str, default=False, required=False, help="...")

1 Answer 1

1

I learned that this is possible, but you need to use the const and nargs options.

parser.add_argument('-o', '--output', const='default.txt', nargs='?', type=str, default=False, required=False, help="...")

Read more: const nargs

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

1 Comment

Nice: I wasn't aware of const being used apart from store_const or append_const actions.

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.