Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value of commandline parameters when no value is provided [duplicate]

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.

like image 930
Rgeek Avatar asked Jun 17 '14 19:06

Rgeek


People also ask

Which parameters are default values?

The default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.

Can parameters have default values?

Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.

What is the type specification of the command line arguments by default in Python?

Python sys module stores the command line arguments into a list, we can access it using sys. argv . This is very useful and simple way to read command line arguments as String. Let's look at a simple example to read and print command line arguments using python sys module.


1 Answers

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)
like image 63
unutbu Avatar answered Oct 13 '22 01:10

unutbu