I want to distinguish between these three cases:
- The flag is not present at all
python example.py
; - The flag is present but without a value
python example.py -t
; and - The flag is present and has a value
python example.py -t ~/some/path
.
How can I do this with Python argparse
? The first two cases would be covered by action='store_true'
but then the third case becomes invalid.
You can do this with
nargs='?'
:Your three cases would give:
default
value;const
value; and'~/some/path'
respectively. For example, given the following simple implementation:
You'd get this output: