Python argparse General Use Guide

argparse is Python’s standard library module for creating command-line interfaces. It’s a powerful tool for parsing command-line arguments and generating help messages.

Basic Usage Pattern

 1import argparse
 2
 3# 1. Create the parser
 4parser = argparse.ArgumentParser(description='Description of your program')
 5
 6# 2. Add arguments
 7parser.add_argument('--foo', help='foo help')
 8parser.add_argument('bar', help='bar help')
 9
10# 3. Parse the arguments
11args = parser.parse_args()
12
13# 4. Use the arguments
14print(args.foo)
15print(args.bar)

Adding Arguments

Positional Arguments

1parser.add_argument('filename', help='name of the file to process')

Optional Arguments

1parser.add_argument('--verbose', '-v', help='increase output verbosity', action='store_true')

Common Argument Types

 1# String (default)
 2parser.add_argument('--name', type=str, help='person name')
 3
 4# Integer
 5parser.add_argument('--age', type=int, help='person age')
 6
 7# Float
 8parser.add_argument('--price', type=float, help='item price')
 9
10# Boolean flags
11parser.add_argument('--enable', action='store_true', help='enable feature')
12parser.add_argument('--disable', action='store_false', help='disable feature')
13
14# Choices
15parser.add_argument('--color', choices=['red', 'green', 'blue'], help='color choice')
16
17# Multiple values
18parser.add_argument('--numbers', nargs='+', type=int, help='list of numbers')

Advanced Options

 1# Required arguments
 2parser.add_argument('--required-arg', required=True, help='this argument is required')
 3
 4# Default values
 5parser.add_argument('--delay', type=int, default=10, help='delay in seconds')
 6
 7# Custom actions
 8parser.add_argument('--version', action='version', version='%(prog)s 1.0')
 9
10# Argument groups
11group = parser.add_argument_group('authentication')
12group.add_argument('--username', help='username')
13group.add_argument('--password', help='password')

Parsing and Using Arguments

1args = parser.parse_args()
2
3# Access argument values
4if args.verbose:
5    print("Verbose mode enabled")
6
7if args.filename:
8    process_file(args.filename)

Subcommands

For complex CLI tools with multiple commands (like git):

 1# Create top-level parser
 2parser = argparse.ArgumentParser(prog='PROG')
 3subparsers = parser.add_subparsers(help='sub-command help')
 4
 5# Create parser for "install" command
 6parser_install = subparsers.add_parser('install', help='install help')
 7parser_install.add_argument('package', help='package to install')
 8parser_install.set_defaults(func=install_command)
 9
10# Create parser for "remove" command
11parser_remove = subparsers.add_parser('remove', help='remove help')
12parser_remove.add_argument('package', help='package to remove')
13parser_remove.set_defaults(func=remove_command)
14
15# Parse and dispatch
16args = parser.parse_args()
17if hasattr(args, 'func'):
18    args.func(args)
19else:
20    parser.print_help()

Help and Usage Messages

argparse automatically generates help messages:

1$ python script.py -h
2$ python script.py --help

Customize the help text with:

1parser = argparse.ArgumentParser(
2    prog='ProgramName',
3    description='What the program does',
4    epilog='Text at the bottom of help'
5)

Example: Complete Program

 1import argparse
 2
 3def main():
 4    parser = argparse.ArgumentParser(description='Process some integers.')
 5    
 6    parser.add_argument('integers', metavar='N', type=int, nargs='+',
 7                       help='an integer for the accumulator')
 8    parser.add_argument('--sum', dest='accumulate', action='store_const',
 9                       const=sum, default=max,
10                       help='sum the integers (default: find the max)')
11    
12    args = parser.parse_args()
13    print(args.accumulate(args.integers))
14
15if __name__ == '__main__':
16    main()

Usage:

1$ python prog.py 1 2 3 4
24
3$ python prog.py 1 2 3 4 --sum
410

This guide covers the most common use cases for argparse. The module offers even more customization options for complex CLI applications.

Appendix: A sample for a model trainer

 1if __name__ == "__main__":
 2  parser = argparse.ArgumentParser()
 3
 4  parser.add_argument(
 5    "--mode",
 6    type=str,
 7    default="train",
 8    help="Operation mode, `train` or `eval`.",
 9  )
10  parser.add_argument(
11    "--config_mode",
12    type=str,
13    default="nomad",
14    help="Config preset mode, `nomad` or `debug`.",
15  )
16  parser.add_argument(
17    "--checkpoint_dir",
18    type=str,
19    default=None,
20    help="Directory location for storing checkpoints, default value as `None` would automatically set a location.",
21  )
22
23  # Cache the args excluded in the above code
24  args = parser.parse_args()
25  dict_args = vars(args)
26  kwargs = {
27    key: val
28    for key, val in dict_args.items()
29    if key not in ["mode", "config_mode", "checkpoint_dir"] and val is not None
30  }
31
32  if args.mode == "train":
33    train(args.config_mode, args.checkpoint_dir, kwargs)
34  elif args.mode == "eval":
35    pass
36  else:
37    raise argparse.ArgumentError(
38      "mode should be set to either `train` or `eval`."
39    )