tyleax
tyleax

Reputation: 1788

How to set default values for argparse metavar arguments?

I am using argparse so my python script can take in arguments. With argparse, I'm using metavar so I can take in 2 arguments for a single flag. I want to be able to set default values for these arguments if they are not specified. How can I set default values to my metavar arguments?

parser = argparse.ArgumentParser(description='Sample ArgumentParser')    
parser.add_argument("--stuff", nargs=2, metavar=('arg1', 'arg2'))

Upvotes: 1

Views: 1614

Answers (1)

Ben
Ben

Reputation: 6358

As @hpaulj says, just use the default parameter:

import argparse

parser = argparse.ArgumentParser(description='Sample ArgumentParser')
parser.add_argument(
    "--stuff",
    nargs=2,
    metavar=('arg1', 'arg2'),
    default=('arg1def', 'arg2def')
)

args = parser.parse_args()
print('Args:', args)

Output:

λ python tmp.py
Args: Namespace(stuff=('arg1def', 'arg2def'))

λ python tmp.py --stuff bob ross
Args: Namespace(stuff=['bob', 'ross'])

Upvotes: 3

Related Questions