14

I am using ArgParse for giving commandline parameters in Python.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--quality", type=int,help="enter some quality limit")
args = parser.parse_args()
qual=args.quality

if args.quality:
  qual=0

$ python a.py --quality 

a.py: error: argument --quality: expected one argument

In case of no value provided,I want to use it as 0,I also have tried to put it as "default=0" in parser.add_argument,and also with an if statement.But,I get the error above.

Basically,I want to use it as a flag and give a default value in case no value is provided.

0

3 Answers 3

16

Use nargs='?' to allow --quality to be used with 0 or 1 value supplied. Use const=0 to handle script.py --quality without a value supplied. Use default=0 to handle bare calls to script.py (without --quality supplied).

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--quality", type=int, help="enter some quality limit",
                    nargs='?', default=0, const=0)
args = parser.parse_args()
print(args)

behaves like this:

% script.py 
Namespace(quality=0)
% script.py --quality
Namespace(quality=0)
% script.py --quality 1
Namespace(quality=1)
Sign up to request clarification or add additional context in comments.

Comments

1

Have a loot at https://docs.python.org/2/howto/argparse.html#id1. Simply add the argument default to your add_argument call.

parser.add_argument("--quality", type=int, default=0, nargs='?', help="enter some quality limit")

If you want to use --quality as a flag you should use action="store_true". This will set args.quality to True if --quality is used.

Comments

-1

With docopt use [default: 0] in docstring

Deliberately ignoring the argparse part of your question, here is how you could define default using docopt.

With docopt you define default value (and almost all the rest) as part of docstring.

First, install docopt and for validating values also schema

$ pip install docopt schema

Then write the script a.py:

"""
Usage:
    a.py [--quality <qlimit>]
    a.py -h

Options:
    --quality=<qlimit>  Quality limit [default: 0]
"""
def main(quality):
    print "FROM MAIN: minimal quality was set to", quality

if __name__ == "__main__":
    from docopt import docopt
    from schema import Schema, And, Use, SchemaError
    args = docopt(__doc__)
    print args
    schema = Schema({
        "--quality": 
        And(Use(int), lambda n: 0 <= n, error="<qlimit> must be non-negative integer"),
        "-h": bool
    })
    try:
        args = schema.validate(args)
    except SchemaError as e:
        exit(e)
    quality = args["--quality"]
    main(quality)

and use the script, first asking for help string:

$ python a.py -h
Usage:
    a.py [--quality <qlimit>]
    a.py -h

Options:
    --quality=<qlimit>  Quality limit [default: 0]

Then use it using default value:

$ python a.py
{'--quality': '0',
 '-h': False}
FROM MAIN: minimal quality was set to 0

setting non-default correct one to 5:

$ python a.py --quality 5
{'--quality': '5',
 '-h': False}
FROM MAIN: minimal quality was set to 5

trying not allowed negative value:

$ python a.py --quality -99
{'--quality': '-99',
 '-h': False}
<qlimit> must be non-negative integer

or non integer one:

$ python a.py --quality poor
{'--quality': 'poor',
 '-h': False}
<qlimit> must be non-negative integer

Note, that as soon as the validate step passes, the value for "--quality" key is already converted to int.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.