2

I used the OptParse module a few years back, and it seemed so easy, but seeing the argparse module, it doesn't seem intuitive to use. Thus, I'd like some help.

I currently have (which isnt much yet):

import argparse
parser = argparse.ArgumentParser()
parser.parse_args()

I'd like to be able to issue a command like python myscript.py --char 20 . This value for char flag will always be an int.

If someone can please help, I'd greatly appreciate it! Thank you

3
  • Have you considered adding the argument you want to take to the parser? What's the problem? Commented Nov 19, 2015 at 0:54
  • 1
    I think a quick Google search answers this question the best. Commented Nov 19, 2015 at 0:56
  • This task isn't significantly different between optparse and argparse. Commented Nov 19, 2015 at 2:15

2 Answers 2

2

This is how you add an argument, and retrieve it:

import argparse
parser = argparse.ArgumentParser()

parser.add_argument('--char', type=int,
                   help='number of characters')

args = parser.parse_args()
char = args.char

You should check out the docs: https://docs.python.org/3/library/argparse.html

And here's a tutorial: https://docs.python.org/2/howto/argparse.html

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

1 Comment

There's a section at the end of the argparse docs about translating optparse to argparse.
1

you need to add an argument to the parser object, and optionally specify the parameter type to be int

# testargs.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--char', type=int)
args = parser.parse_args()

print(args.char)

if you execute this file with

python testargs.py --char 20

it should print 20 to the console

1 Comment

Just a point of caution: type=int means, "use the int() function to convert the string to a number". This expression is similar to, but not quite the same as the optparse parser.add_option("-n", type="int", dest="num").

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.