Nico Schlömer
Nico Schlömer

Reputation: 58951

argparse: setting optional argument with value of mandatory argument

With Python's argparse, I would like to add an optional argument that, if not given, gets the value of another (mandatory) argument.

parser.add_argument('filename',
                    metavar = 'FILE',
                    type    = str,
                    help    = 'input file'
                    )

parser.add_argument('--extra-file', '-f',
                    metavar = 'ANOTHER_FILE',
                    type    = str,
                    default = ,
                    help    = 'complementary file (default: FILE)'
                    )

I could of course manually check for None after the arguments are parsed, but isn't there a more pythonic way of doing this?

Upvotes: 21

Views: 8797

Answers (2)

chepner
chepner

Reputation: 532538

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.

Upvotes: 2

mgilson
mgilson

Reputation: 310307

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").

Upvotes: 19

Related Questions