I'm trying to implement the following behavior for the CLI for my Python script:
- if the
-ooption is not present, the script does not write to a file - if the
-ooption is present without an argument, the script writes to a default filename - if the
-ooption 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="...")