Rgeek
Rgeek

Reputation: 449

Extract names of Command line parameter in a function

I am using ArgParse for giving commandline parameters in Python.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--quality", help="enter some quality limit")
args = parser.parse_args()
print "You gave quality = %s" % str(args.quality)

def is_number(s):
   try:
      val = int(s)
   except ValueError:
      print "That is not an int!"

is_number(args.quality)

I saved this as a.py then ran this:

$python a.py --quality 10
You gave quality = 10

In case we enter some character instead of a number,I want to print out the argument name "quality" in the print statement inside the function "quality is not an int".How can I extract the name of the argument and use it there.I have some more commandline paramters,so I want an explicit error stating which parameter is not an int.

Upvotes: 1

Views: 161

Answers (1)

kindall
kindall

Reputation: 184101

One way is to rewrite your is_number to take the argument name as a string.

def is_number(args, argname):
    try:
        int(getattr(args, argname))
    except ValueError:
        print argname, "is not an integer"

is_number(args, "quality")

But Ben's suggestion to use argparse's type argument is better.

Upvotes: 2

Related Questions