Understand Python action=”store_true” in argparse.ArgumentParser with Example – Python Tutorial

By | January 31, 2024

ArgumentParser can allow us to run python script by command line. Here is the tutorial:

Python ArgumentParser: Create and Parse Command Line Arguments – Python Tutorial

However, we may find action=”store_true” in add_argument(). In this tutorial, we will introduce what it mean and how to use it.

For example:

import argparse
# Command Line Arguments
parser = argparse.ArgumentParser(description='main program')
parser.add_argument('--base_model', type=str,
                    help='Path to or name of base model')
parser.add_argument('--model_type', type=str, default="llama",
                    help='The model type, support: llama, chatglm')
parser.add_argument('--inference', action="store_true",
                    help='The inference mode (just for test)')

args = parser.parse_args()
print(args.inference)

If we run this python code as follows:

python test5-33.py

Because we have not set default value for –inference, we will see:

False

If we run this code by this:

python test5-33.py --inference

We will see:

True

However, if we set a default value for –inference

parser.add_argument('--inference', action="store_true", default=True,
                    help='The inference mode (just for test)')

args = parser.parse_args()
print(args.inference)

Run this code by python test5-33.py, we will see:

True