dropWizard
dropWizard

Reputation: 3538

Passing a string using argparse

I've been reading through the documentation and the tutorial, but there is one thing I don't quite understand.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("test string", type=str, help="this is a string")
args = parser.parse_args()
print args

When I run $python prog.py 'test' the result is:

Namespace(test string='test')

How do I get it to print just test?

Upvotes: 1

Views: 5057

Answers (3)

user1245262
user1245262

Reputation: 7505

I don't understand everything that is going on with your code, but having a space in the name of your argument seems to be a bad idea. If I use the following code:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("test_string", type=str, help="this is a string")
args = parser.parse_args()
print args.test_string

then

python temp3.py test

gives me what you want.

when you create the "test string" name for the argument it is not clear (at least to me) how you can access its value using the 'dot' notation.

Upvotes: 0

Bryan Oakley
Bryan Oakley

Reputation: 385970

It's highly unusual to use a name with a space in it, since it makes it difficult to get values back out.

The documentation has this to say about the object that is returned from parse_args:

This class is deliberately simple, just an object subclass with a readable string representation. If you prefer to have dict-like view of the attributes, you can use the standard Python idiom, vars()

So, to treat args like a dictionary you can do something like this:

print var(args)["test string"]

You can also do it this way:

print getattr(args, "test string")

Note that if your option does not have spaces in it (eg: "teststring") you can access the attribute directly:

print args.teststring

Upvotes: 1

master_Alish
master_Alish

Reputation: 383

Maybe you want something like this:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("teststring", type=str, help="this is a string")
args = parser.parse_args()
print args.teststring

Upvotes: 4

Related Questions