argparse: setting optional argument with value of mandatory argument
As far as I know, there is no way to do this that is more clean than:
ns = parser.parse_args()ns.extra_file = ns.extra_file if ns.extra_file else ns.filename
(just like you propose in your question).
You could probably do some custom action gymnastics similar to this, but I really don't think that would be worthwhile (or "pythonic").
This has slightly different semantics than your original set of options, but may work for you:
parse.add_argument('filename', action='append', dest='filenames')parse.add_argument('--extra-file', '-f', action='append', dest='filenames')args = parse.parse_args()
This would replace args.filename
with a list args.filenames
of at least one file, with -f
appending its argument to that list. Since it's possible to specify -f
on the command line before the positional argument, you couldn't on any particular order of the input files in args.filenames
.
Another option would be to dispense with the -f
option and make filename
a multi-valued positional argument:
parse.add_argument('filenames', nargs='+')
Again, args.filenames
would be a list of at least one filename. This would also interfere if you have other positional arguments for your script.