Ways To Parse Boolean Values With Argparse in Python

In this article, we are going to learn how to parse boolean values with argparse in python. After reading this article, we will know about argparse in python. Argparse is a way of adding positional or optional arguments to the code. Let us move to learn about argparse python.

The argparse is a standard python library that is useful to do some manipulations in the command line. This module helps to improve interaction, and it is easy to code. When the user gives some invalid arguments, it generates a help and usage message to the user. And also, it displays issues errors to the user. The argparse module is user-friendly. The store_true option has a default value False. Likewise, store_false has a default value True. We have to follow three important steps to use the argparse module. First, creating a parser. Secondly, adding arguments to the parser. Finally, parsing arguments.

How to Create a Parser?

First, we have to import a module argparser. After importing argparser, the parser will be created. The parser will store all the information that has to pass.

Syntax

class argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars=’-‘, fromfile_prefix_chars=None, argument_default=None, conflict_handler=’error’, add_help=True, allow_abbrev=True)

Parameters

  • prog: name of the program
  • usage: program usage
  • description: a brief description will be displayed before the command help.
  • epilog: a group of statements that will be displayed after the command help
  • parents: list of argument parser
  • formatter_class: class
  • prefix_chars: a set of prefix characters
  • fromfile_prefix_chars: a set of prefix files
  • argument_default: global default value
  • conflict_handler: resolving conflicting options
  • add_help: Add a help option to the parser
  • allow_abbrev: Allow long options

How to add arguments?

After creating the parser, we have to add the arguments. Arguments have to be filled with information about the arguments. Using add_argument() method to add the argument. This tells how to take the argument from the command line.

Syntax

ArgumentParser.add_argument(name or flags…[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])

Parameter

  • names or flags: name of a string
  • action: action that has to be taken when the arguments are passed.
  • nargs: number of command-line arguments
  • const: constant value
  • default: default value produced if the arguments are absent.
  • type: In which type the argument should convert
  • choices: allowable values
  • required: options only
  • help: it is a brief description of what the argument does
  • metavar: name of an argument
  • dest: name of an attribute

How to parse arguments?

First, it will gather the information and will use it when the arguments are parsed. The arguments will be parsed through parse_args(). While parse_args() is called the command line, data convert them into the required data type. After converting, it produces a proper result.

Syntax

ArgumentParser.parse_args(args=None, namespace=None)

Parameter

  • args – list of strings
  • Namespace – object to take attributes.

Must Read | Scipy fsolve

Code 1: Parsing arguments as boolean values

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--Var1', action='store_true')
parser.add_argument('--Var2', action='store_false')
arguments = parser.parse_args()
print(arguments)

First, importing the argparse module. Secondly, creating a parser. Thirdly, passing ArgumentParser(). Fourthly, adding arguments variable 1 and variable 2. One variable stores action 1 as True, and another variable action is False.

Output

Namespace(Var1=False, Var2=True)

Code 2: Parsing arguments using conditional statements

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--do-something", default=False, action="store_true")
arguments = parser.parse_args()
if arguments.do_something:
     print("Do something")
else:
     print("Don't do something")
print(f"Check that arguments.do_something={arguments.do_something} is always a boolean value.")

First, importing the argparse module. Secondly, creating a parser. Thirdly, passing ArgumentParser(). Fourthly, parsing commands like Do something and don’t something. Finally, checking for the results.

Output

Don't do something
Check that arguments.do_something=False is always a boolean value.

Code 3: Simplest way to parse boolean arguments

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--my-flag',choices=('True','False'))
arguments = parser.parse_args()
MyFlag = arguments.my_flag == 'True'
print(MyFlag)

First, importing the argparse module. Secondly creating a parser. Thirdly passing ArgumentParser(). Fourthly adding arguments in the parser. Using flags to add arguments.

Output

False

Code 4: Parsing arguments using distuils module

import argparse
from distutils.util import strtobool
parser = argparse.ArgumentParser()
parser.add_argument("--flag", type=lambda x:bool(strtobool(x)),
    nargs='?', const=True, default=False)
arguments = parser.parse_args()
print(arguments.flag)

First, importing the argparse module. Secondly, creating a parser. Thirdly, importing strtobool from distutils module. Fourthly, adding arguments to the parser. Using flags to add arguments. Now the argparse bool will be displayed.

Output

False

Code 5: Parsing arguments using disutils module with conditional statements

import argparse
from distutils.util import strtobool
parser = argparse.ArgumentParser()
parser.add_argument("--feature", type=str, nargs='?', const='True', default="False")
arguments = parser.parse_args()
if bool(strtobool(arguments.feature)) is True:
    print(" ")
print(arguments.feature)

First, importing argparse. Secondly, creating a parser. Thirdly, importing strtobool from distutils module. Fourthly, adding arguments to the parser. Using conditional statement to parse the argparse.

Output

False

1. What is the argparse module?

argparse is a module that is useful to parse command-line arguments.

2. What are the steps for using the argparse module?

First, we have to create the parser. Secondly, we have to add arguments to the parse. Thirdly, we have to parse arguments.

3. What is the command line to install the argparse module?

pip install argparse module

Conclusion

Here we have completely learned about argparse boolean python. We hope now you are all well known about argparse bool python. This article covers the steps for using the argparse module. How to parse the boolean value with the argparse module? Try to solve the code on your own. Learn python coding with us 🙂

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments