My Program should include the following options, properly parsed by argparse:
- purely optional:
[-h, --help]
and[-v, --version]
- mutually exclusive:
[-f FILE, --file FILE]
and[-u URL, --url URL]
- optional if
--url
was chosen:[-V, --verbose]
- required if either
--file
or--url
was chosen:[-F, --format FORMAT]
The desired usage pattern would be:
prog.py [-h] [-v] [-f FILE (-F FORMAT) | -u URL [-V] (-F FORMAT) ]
with the -F
requirement applying to both members of the mutually exclusive group.
Not sure if it rather be a positional.
So it should be possible to run:
prog.py -u "http://foo.bar" -V -F csv
and the parser screaming in case i forgot the -F
(as he's supposed to).
What i've done so far:
parser = ArgumentParser(decription='foo')
group = parser.add_mutually_exclusive_group()
group.add_argument('-f','--file', nargs=1, type=str, help='')
group.add_argument('-u','--url', nargs=1, type=str, help='')
parser.add_argument('-V','--verbose', action='store_true', default=False, help='')
parser.add_argument('-F','--format', nargs=1, type=str, help='')
Since it has a 'vanilla mode' to run without command line arguments, all arguments must be optional.
How can i implement points 3. and 4. into my code?
EDIT:
I tried -f
and -u
as subparsers, as described here, but subcommands seem to be treated like positionals and the parser gives me an error: too few arguments
if i run it without arguments.