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 argumentsconst=1sets the default when there are 0 argumentstype=intconverts 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)
Answer from unutbu on Stack Overflowimport 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 argumentsconst=1sets the default when there are 0 argumentstype=intconverts 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)
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
Why/how does "%(default)s" display default arg in argparse help text?
Argparse: "Default" interacts incorrectly/non-intuitively with action='append' and action='extend'
argparse default values
What's the point of argparse if you can use input?
Videos
The premise behind your question is mistaken.
>>> import argparse
>>> p = argparse.ArgumentParser()
>>> p.add_argument('-a')
>>> p.parse_args()
Namespace(a=None)
The -a argument is already optional by default (you don't need required=False), and its default is already None, ensuring that args.a exists without any manual intervention.
You have to opt-in to having no default at all.
>>> p.add_argument("-b", default=argparse.SUPPRESS)
>>> p.parse_args()
Namespace(a=None)
So yes, it probably is a good idea to have some default, and argparse acknowledges that by providing one.
So some clarifications here. To answer this question for python specifically, argparse does in fact default optional argument values to None. Your problem arises from having multiple subcommands that take different arguments, but go through the same code flow. If you pass the same args from subcommands a, b, c that have different options, then you do have to handle each option that is not common across all three. In that workflow, I would recommend backfilling each option that is not guaranteed to exist.
Here is a snippet of example code. Pretend this is at the top of a file script.py:
import argparse
DEFAULT_ARG = 'How can a clam cram in a clean cream can?'
parser = argparse.ArgumentParser()
parser.add_argument('--some_arg',
default=DEFAULT_ARG,
help='some random argument (default: %(default)s)')
args = parser.parse_args()
If you then run python script.py --help, you see the following:
usage: script.py [-h] [--some_arg SOME_ARG] optional arguments: -h, --help show this help message and exit --some_arg SOME_ARG some random argument (default: How can a clam cram in a clean cream can?)
Notice how in the final line, %(default)s was expanded to the value of DEFAULT_ARG, the default argument for args.some_arg. I saw this hack a year or so ago on SO as a way to get argparse to dynamically show an argument's default value without any bespoke modification to the ArgumentParser's formatter_class arg. I've done it this way ever since because it's so dead easy. But I never stopped to wonder how/why it actually works, until now.
Can someone explain what's going on? How does Python know that the default in the middle of the help string == the default argument going into parser.add_argument? I'm pretty proficient with Python but I guess underlyingly this is a feature I never learned about. Also, if there is a better/more recommended/more modern way to achieve the same (i.e., default values displayed in the help text), I'd love to know. Thanks!
I have a script that consists of several flags. Each flag, when stated following a filename, is set to true and runs a specific function.
prog.py myfile.txt -f
The above performs a specific function on myfile.txt that the -f flag is referring to. But I also want to be able to add arguments to the flag, so I set nargs=2.
prog.py myfile.txt -f 100 500
The above will run the program with myfile.txt and the arguments 100 and 500. No problems so far.
My issue is that I want to make it possible to run the same script even if no arguments are given. As in the first code, the script should run prog.py and perform the function that -f is referring to, but with default values, such as 10 and 50.
Now I know I could use Default when I add the argument to argparse, but then it will only use the default values if the -f flag is omitted. This is an issue because my script has many functions, and I want it to be capable of running a specific function depending on the flag that is used.
Basicallt I want the user to be able to perform function -f with or without any arguments, is there some way to achieve this?
I'm on Debian 8.7.1 using Python 2.7.13.