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.
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.
Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With