argparse is a command-line parsing module of Python for parsing command-line arguments. It provides a simple and flexible way to handle command-line arguments, helping developers build more powerful command-line interfaces.
1. Create an ArgumentParser object:
import argparse
parser = argparse.ArgumentParser()
2. Add command line parameters:
parser.add_argument('--name', help='enter your name')
The method is used here add_argument
to add a command line argument. --name
It is the name of the parameter, and help
it is the help information of the parameter.
3. Parse the command line parameters:
args = parser.parse_args()
parse_args()
method is used to parse command-line arguments and return a namespace object containing the argument values.
4. Obtain the value of the command line parameter:
print(args.name)
The value of a command-line argument can be obtained by accessing the properties of the namespace object.
5. Add positional parameters:
parser.add_argument('filename', help='enter the filename')
Here filename
is a positional parameter, it does not need to be prefixed with --
or -
and must be provided in the specified positional order.
6. Set the type of parameter:
parser.add_argument('--count', type=int, help='enter the count')
Parameters can be used type
to specify the type of the parameter, such as integer, floating point, etc.
7. Set the default value of the parameter:
parser.add_argument('--count', type=int, default=1, help='enter the count')
Parameters can be used default
to set default values for parameters.
8. Add mutually exclusive parameters:
group = parser.add_mutually_exclusive_group()
group.add_argument('--verbose', action='store_true')
group.add_argument('--quiet', action='store_true')
Use add_mutually_exclusive_group()
method to create a mutually exclusive parameter group, where --verbose
and --quiet
are mutually exclusive options.
9. Add mandatory parameters:
parser.add_argument('filename', type=str, help='enter the filename', required=True)
Use required=True
Parameters to make a positional parameter mandatory.
Sample code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--s', type=str, default='a')
parser.add_argument('--m', type=int, default=5)
parser.add_argument('--i', type=int, default=5)
args = parser.parse_args()
print(type(args.s), type(args.m), type(args.i))
print(args.s, args.m, args.i)
operation result:
Reference blog post: