is there a way to create argument in python's argparse that returns true in case no values given

  • Last Update :
  • Techknowledgy :

In order to optionally accept a value, you need to set nargs to '?'. This will make the argument consume one value if it is specified. If the argument is specified but without value, then the argument will be assigned the argument’s const value, so that’s what you need to specify too:

parser = argparse.ArgumentParser()
parser.add_argument('--resize', nargs = '?',
   const = True)

Not specified: The argument will get its default value (None by default):

>>> parser.parse_args(''.split())
Namespace(resize = None)

Specified without a value: The argument will get its const value:

>>> parser.parse_args('--resize'.split())
Namespace(resize = True)

Since you are looking for an index, you can also specify type=int so that the argument value will be automatically parsed as an integer. This will not affect the default or const case, so you still get None or True in those cases:

>>> parser = argparse.ArgumentParser() >>>
   parser.add_argument('--resize', nargs = '?', type = int,
      const = True) >>>
   parser.parse_args('--resize 123'.split())
Namespace(resize = 123)

Your usage would then look something like this:

if args.resize is True:
   for object in my_objects:
   object.do_resize()
elif args.resize:
   my_objects[args.resize].do_resize()

Not specified: The argument will get its default value (None by default):

>>> parser.parse_args(''.split())
Namespace(resize = None)

Specified without a value: The argument will get its const value:

>>> parser.parse_args('--resize'.split())
Namespace(resize = True)

Specified with a value: The argument will get the specified value:

>>> parser.parse_args('--resize 123'.split())
Namespace(resize = '123')
parser.add_argument('-resize', dest = 'resize', type = int, nargs = '?',
      default = False,
      const = True)

   >>
   tmp.py - resize 1
args.resize: 1

   >>
   tmp.py - resize
args.resize: True

   >>
   tmp.py
args.resize: False

Suggestion : 2

The first step in using the argparse is creating an ArgumentParser object:,'store_true' and 'store_false' - These are special cases of 'store_const' used for storing the values True and False respectively. In addition, they create default values of False and True respectively. For example:,Sometimes it may be useful to have an ArgumentParser parse arguments other than those of sys.argv. This can be accomplished by passing a list of strings to parse_args(). This is useful for testing at the interactive prompt:,The const argument of add_argument() is used to hold constant values that are not read from the command line but are required for the various ArgumentParser actions. The two most common uses of it are:

import argparse

parser = argparse.ArgumentParser(description = 'Process some integers.')
parser.add_argument('integers', metavar = 'N', type = int, nargs = '+',
   help = 'an integer for the accumulator')
parser.add_argument('--sum', dest = 'accumulate', action = 'store_const',
   const = sum,
   default = max,
   help = 'sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))
$ python prog.py - h
usage: prog.py[-h][--sum] N[N...]

Process some integers.

positional arguments:
   N an integer
for the accumulator

options:
   -h, --help show this help message and exit
   --sum sum the integers(
      default: find the max)
$ python prog.py 1 2 3 4
4

$ python prog.py 1 2 3 4--sum
10
$ python prog.py a b c
usage: prog.py[-h][--sum] N[N...]
prog.py: error: argument N: invalid int value: 'a'
>>> parser = argparse.ArgumentParser(description = 'Process some integers.')
>>> parser.add_argument('integers', metavar = 'N', type = int, nargs = '+',
      ...help = 'an integer for the accumulator') >>>
   parser.add_argument('--sum', dest = 'accumulate', action = 'store_const',
      ...
      const = sum,
      default = max,
      ...help = 'sum the integers (default: find the max)')

Suggestion : 3

5 days ago Feb 19, 2020  · Argparse Module. The argparse module in Python helps create a program in a command-line-environment in a way that appears not only easy to code but also improves interaction. The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.. Steps for Using Argparse. … , Example - In the following example, we create a simple Python program to perform the add operation using the argparse module. We will pass the argument through the command-line interface. parser = argparse.ArgumentParser () , The “-l” is knowns as an “optional argument”. Using the python argparse module we can create custom positional and optional arguments. Ready to gain a competitive advantage with Future Ready Emerging Technologies? The argparse module makes it easy to write user-friendly command-line interfaces. ,The display of third-party trademarks and trade names on this site does not necessarily indicate any affiliation or endorsement of FaqCode4U.com.


parser.add_argument("--resize", action = "store_true", help = "Do dictionary resize") #...#
if resize flag is true I 'm re-sizing all objects if args.resize:     for object in my_obects:         object.do_resize() 

parser = argparse.ArgumentParser() parser.add_argument('--resize', nargs = '?',
   const = True)

>>> parser.parse_args(''.split()) Namespace(resize = None)

>>> parser.parse_args('--resize'.split()) Namespace(resize = True)

>>> parser.parse_args('--resize 123'.split()) Namespace(resize = '123')
parser.add_argument("--resize", action = "store_true", help = "Do dictionary resize") #...#
if resize flag is true I 'm re-sizing all objects if args.resize:for object in my_obects:  object.do_resize() 

Suggestion : 4

last modified August 20, 2022

1._
#!/usr/bin/python

import argparse

# help flag provides flag help
# store_true actions stores argument as True

parser = argparse.ArgumentParser()

parser.add_argument('-o', '--output', action = 'store_true',
   help = "shows output")

args = parser.parse_args()

if args.output:
   print("This is some output")

The example adds one argument having two options: a short -o and a long --ouput. These are optional arguments.

import argparse

The module is imported.

parser.add_argument('-o', '--output', action = 'store_true',
   help = "shows output")

The arguments are parsed with parse_args. The parsed arguments are present as object attributes. In our case, there will be args.output attribute.

if args.output:
   print("This is some output")

If the argument is present, we show some output.

$ optional_arg.py - o
This is some output
$ optional_arg.py--output
This is some output

Suggestion : 5

March 12, 2018 at 9:22 pm,March 12, 2018 at 6:00 pm,March 12, 2018 at 5:23 pm,March 12, 2018 at 4:15 pm

You can absolutely hardcode paths if you wish. If you’re using a Jupyter Notebook this is also advisable. For any other readers interesting in trying this approach I would suggest taking this code:

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--input", required = True,
   help = "path to input image")
ap.add_argument("-o", "--output", required = True,
   help = "path to output image")
args = vars(ap.parse_args())

And replacing it with:

args = {
   "input": "path/to/input_image.jpg",
   "output": "path/to/output_image.jpg"
}

Using “sudo” will install the package into the system Python virtual environment which you do not want. Try this instead:

$ workon your_env_name
$ pip install imutils

Are you using Python virtual environments? If so, make sure you install it into the proper virtual environment:

$ workon your_env_name
$ pip install imutils