close

[Solved] Python argparse: default value or specified value

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Python argparse: default value or specified value in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Python argparse: default value or specified value Error Occurs?

Today I get the following error Python argparse: default value or specified value in python.

How To Solve Python argparse: default value or specified value Error ?

  1. How To Solve Python argparse: default value or specified value Error ?

    To Solve Python argparse: default value or specified value Error If you want test.py to set example to 1 even if no --example is specified, then include default=1. That is, with

  2. Python argparse: default value or specified value

    To Solve Python argparse: default value or specified value Error If you want test.py to set example to 1 even if no --example is specified, then include default=1. That is, with

Solution 1

The difference between:

parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1, default=7)

and

parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1)

is thus:

myscript.py => debug is 7 (from default) in the first case and “None” in the second

myscript.py --debug => debug is 1 in each case

myscript.py --debug 2 => debug is 2 in each case

Solution 2

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--example', nargs='?', const=1, type=int)
args = parser.parse_args()
print(args)

% test.py 
Namespace(example=None)
% test.py --example
Namespace(example=1)
% test.py --example 2
Namespace(example=2)

  • nargs='?' means 0-or-1 arguments
  • const=1 sets the default when there are 0 arguments
  • type=int converts the argument to int

If you want test.py to set example to 1 even if no --example is specified, then include default=1. That is, with

parser.add_argument('--example', nargs='?', const=1, type=int, default=1)

then

% test.py 
Namespace(example=1)

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read