4

How do you pass a string as an argument in python without the output containing "Namespace".

Here is my code:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("person", help="person to test",type=str)
person = str(parser.parse_args())
print "The person's name is " + person 

Here is the command I am running:

python test.py bob

This is my output:

The person's name is Namespace(person='bob')

I could probably do some fancy splitting, but I'm sure I'm just leveraging the argparse incorrectly(I'm new to python) if anyone can please tell me how to properly pass a string like this I would greatly apreciate it.

3
  • Why not use sys.argv[1] instead? Commented May 16, 2017 at 20:33
  • 3
    Maybe go through the first little bit of the argparse tutorial Commented May 16, 2017 at 20:34
  • There is an awesome library for this called click, check it out click.pocoo.org/5 Commented May 16, 2017 at 20:35

1 Answer 1

11

The namespace is a container for the results of argument parsing. You can access the individual argument values by looking them up in the namespace:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("person", help="person to test",type=str)
args = parser.parse_args()
print "The person's name is " + args.person

The docs have some great examples that show how to use argparse.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This worked like a charm, and your explanation makes perfect sense

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.