Suppose that I have
My program
Usage:
myprog [options]
Options:
-h, --help Show this screen.
--version Show version.
--files=<arg> Files. [default: foo.txt]
I would like to distinguish in my code:
--filesnot specified.--filesspecified, but with no argument to accept the default.--files myfile, i.e.--filesspecified with custom argument.
With the current docstring I can either
- Not specify
--files. - Specify
--fileswith an argument.
So I'm missing:
- The option to specify
--fileswithout an argument. - Distinguish if
--fileswas specified, or if the user specified--files foo.txt
You will need to specify the
--filesargument in the main usage string. For example:This essentially makes
--filesa true/false argument and adds another argumentFNAMEto hold the file name. Usage:Then, you can use the value of
--filesandFNAMEfrom the returneddictto infer what to do:A pitfall to remember: you can also specify
FNAMEindependently of--files. So this also works, and it might interfere with other arguments, so be sure to test all combinations thoroughly:Personally, I prefer using
argparsebecause it's less ambiguous. It builds the doc string from the prescribed arguments, not the other way round.In
argparse, an argument can have a default value and you can specify that it can take zero or one argument usingnargs="?". Then, you can specify aconst="foo.txt"value which the argument will take if no values are given. For example:And running this:
And it even handles the "no
--files" case correctly: