Charles Saag
Charles Saag

Reputation: 631

How to access a variable in argparse with a space in the add_argument function?

import argparse


parser= argparse.ArgumentParser(description='argparse module example')

parser.add_argument('domain name', action='store', nargs=1, help='specify a domain name')

args1 = parser.parse_args()
print(args1['domain name'])

The above code fails. Why? How do I access the domain name input from the command line?

I realize that I could make the argument variable just "domain" and could then access args1.domain but then the output at the command line when incorrect parameters are specified appear as "domain" whereas I want to see "domain name."

ANSWER, which is posted below: use the metavar parameter in the add_argument function.

Upvotes: 0

Views: 851

Answers (2)

hpaulj
hpaulj

Reputation: 231355

With that dest you have a couple of options:

args1 = parser.parse_args(['foobar'])

In [506]: args1
Out[506]: Namespace(**{'domain name': ['foobar']})

convert to dictionary:

In [507]: vars(args1)
Out[507]: {'domain name': ['foobar']}
In [508]: vars(args1)['domain name']
Out[508]: ['foobar']

Use the general purpose getattr:

In [509]: getattr(args1,'domain name')
Out[509]: ['foobar']

argparse uses getattr and setattr to access the Namespace. That way it imposes minimal constraints on the naming of arguments. But to access as

args.foobar

the dest has to be a valid variable name.

And yes, as you answer, with the metavar, there's no real reason for using a more complicated dest.

Upvotes: 1

Charles Saag
Charles Saag

Reputation: 631

Okay, so the answer is to use the parameter metavar='... name ...' in the add_argument() function so that it's displayed differently in -h text.

Upvotes: 0

Related Questions