【CLI】`argument parser` explained
1. What is the argument parser
argument parser
(used as argparse) is a Python module that provides a mechanism for parsing command-line arguments.
You can specify the arguments your program expects and argparse will automatically generate help and usage messages, handle user input, and parse the command-line arguments into Python variables.
2. Example
・Example Code
import argparse
# Create the parser
parser = argparse.ArgumentParser(description="A simple argument parser example")
# Add arguments
parser.add_argument('--name', type=str, help='Your name')
# parser.add_argument('name', type=str, help='Your name')
parser.add_argument('--age', type=int, default=30, help='Your age', required=True)
# Parse the arguments
args = parser.parse_args()
# Access the arguments
print(f"Hello, {args.name}! You are {args.age} years old.")
・Example CLI
python script.py --name Alice --age 25
・Result
Hello, Alex! You are 20 years old.
As you can see, args can treat all arguments from CLI. It's useful!
2.1 Features
The arguments of add_argument() are here.
・'name'
argument name, required.
・'--name'
argument name, option. Not required.
・type
type restrict of arguments
・default
Default value when user doesn't specify the argument.
・required
The argument became required one even with prefix '--', but it have to specify like python script.py --name Bill
. If 'name'(no '--'), you can specify without 'name' like this python script.py Bill
.
・help
The message that be shown when python script.py help
, like this.
python script.py help
# Output
# usage: script.py [-h] [--name NAME] --age AGE
# script.py: error: the following arguments are required: --age
・choices=['red', 'blue', 'green']
Can restrict arguments to a limited set of choices
・action='store_true'
Running the script with --augment_name
sets args.verbose to True
Exclusive Arguments
You can define arguments that cannot be used together using add_mutually_exclusive_group().
group = parser.add_mutually_exclusive_group()
group.add_argument('--verbose', action='store_true')
group.add_argument('--quiet', action='store_true')
3. Summary
This time, I explained about argument parser. It is used in various scene, let you try to use.
Discussion