Parsing Boolean Values with Argparse in Python
Introduction
In this Byte, we'll be looking into Python's argparse
module and how we can use it to parse boolean values from the command line. This is often used when you're writing a command line tool or even a more complex application. Understanding argparse
and its functionalities can make your life a lot easier when taking input from the command line.
The Argparse Module
Argparse is a Python module that makes it easy to write user-friendly command-line interfaces. The argparse
module can handle positional arguments, optional arguments, and even sub-commands. It can also generate usage and help messages, and throw errors when users give the program invalid arguments.
Argparse has been part of the Python standard library since version 2.7, so you don't need to install anything extra to start using it. It's designed to replace the older optparse
module, and offers a more flexible interface.
Basic Usage of Argparse
To start using argparse, you first need to import it:
import argparse
Next, you create a parser
object:
parser = argparse.ArgumentParser(description='My first argparse program.')
The ArgumentParser
object holds all the information necessary to parse the command line into Python data types. The description
argument to ArgumentParser
is a text to display before the argument help (the --help
text).
To add arguments to your program, you use the add_argument()
method:
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)')
Finally, you can parse the command-line arguments with parse_args()
:
args = parser.parse_args()
print(args.accumulate(args.integers))
This will parse the command line, convert each argument to the appropriate type, and then invoke any actions you've specified.
Parsing Boolean Values
Now, let's see how we can parse boolean values with argparse
. For this, we'll use the built-in store_true
or store_false
actions. These actions store the values True
and False
respectively.
import argparse
parser = argparse.ArgumentParser(description='Parse boolean values.')
parser.add_argument('--flag', dest='flag', action='store_true',
help='Set the flag value to True.')
parser.add_argument('--no-flag', dest='flag', action='store_false',
help='Set the flag value to False.')
parser.set_defaults(flag=True)
args = parser.parse_args()
print('Flag:', args.flag)
In this script, we've set up two command-line options: --flag
and --no-flag
. The --flag
option sets args.flag
to True
, and the --no-flag
option sets it to False
. If neither option is given, the set_defaults()
method sets args.flag
to True
.
Here's how it works in the command line:
$ python bool_argparse.py --flag
Flag: True
$ python bool_argparse.py --no-flag
Flag: False
$ python bool_argparse.py
Flag: True
As you can see, argparse
makes it easy to parse boolean values, and even to set default values. This can be very useful in a lot of applications, from simple scripts to more complex command-line interfaces.
Other Ways to Pass Boolean Values via CLI
In addition to the store_true
and store_false
actions, there are other ways you can pass boolean values using the command line interface. One common alternative is to pass the boolean value as a string, and then convert this string to a boolean in your script.
Let's consider the following example:
import argparse
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
parser = argparse.ArgumentParser()
parser.add_argument('--flag', type=str2bool, help='Boolean flag')
args = parser.parse_args()
print(args.flag)
Here we've define a helper function str2bool
that converts a string to a boolean value. It works by checking for common "truthy" and "falsey" values.
We then use this function as the type
for our argument. This allows us to pass boolean values as strings, like this:
$ python script.py --flag yes
True
$ python script.py --flag no
False
Conclusion
In this Byte, we've shown some examples on how to parse boolean values with the argparse
module in Python. We've looked at the basic usage of argparse
, how to parse boolean values, and some alternatives for handling boolean values. Whether you're writing a simple script for personal use or a complex application to be used by others, argparse
is a useful tool to make your script more flexible and user-friendly.