| 1 |
|
| 2 |
"""A comprehensive example demonstrating various aspects of using `argparse` for command argument processing. |
| 3 |
|
| 4 |
Demonstrates basic usage of the `cmd2.with_argparser` decorator for passing a `cmd2.Cmd2ArgumentParser` to a `do_*` command |
| 5 |
method. The `fsize` and `pow` commands demonstrate various different types of arguments, actions, choices, and completers that |
| 6 |
can be used. |
| 7 |
|
| 8 |
The `print_args` and `print_unknown` commands display how argparse arguments are passed to commands in the cases that unknown |
| 9 |
arguments are not captured and are captured, respectively. |
| 10 |
|
| 11 |
The `base` and `alternate` commands show an easy way for a single command to have many subcommands, each of which take |
| 12 |
different arguments and provides separate contextual help. |
| 13 |
|
| 14 |
Lastly, this example shows how you can also use `argparse` to parse command-line arguments when launching a cmd2 application. |
| 15 |
""" |
| 16 |
|
| 17 |
import argparse |
| 18 |
import os |
| 19 |
|
| 20 |
import cmd2 |
| 21 |
from cmd2.string_utils import stylize |
| 22 |
|
| 23 |
|
| 24 |
ARGPARSE_USAGE = "Argparse Basic Usage" |
| 25 |
ARGPARSE_PRINTING = "Argparse Printing" |
| 26 |
ARGPARSE_SUBCOMMANDS = "Argparse Subcommands" |
| 27 |
|
| 28 |
|
| 29 |
class ArgparsingApp(cmd2.Cmd): |
| 30 |
def __init__(self, color: str) -> None: |
| 31 |
"""Cmd2 application for demonstrating the use of argparse for command argument parsing.""" |
| 32 |
super().__init__(include_ipy=True) |
| 33 |
self.intro = stylize( |
| 34 |
"cmd2 has awesome decorators to make it easy to use Argparse to parse command arguments", style=color |
| 35 |
) |
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
fsize_parser = cmd2.Cmd2ArgumentParser(description="Obtain the size of a file") |
| 41 |
fsize_parser.add_argument("-c", "--comma", action="store_true", help="add comma for thousands separator") |
| 42 |
fsize_parser.add_argument("-u", "--unit", choices=["MB", "KB"], help="unit to display size in") |
| 43 |
fsize_parser.add_argument("file_path", help="path of file", completer=cmd2.Cmd.path_complete) |
| 44 |
|
| 45 |
@cmd2.with_argparser(fsize_parser) |
| 46 |
@cmd2.with_category(ARGPARSE_USAGE) |
| 47 |
def do_fsize(self, args: argparse.Namespace) -> None: |
| 48 |
"""Obtain the size of a file.""" |
| 49 |
expanded_path = os.path.expanduser(args.file_path) |
| 50 |
|
| 51 |
try: |
| 52 |
size = os.path.getsize(expanded_path) |
| 53 |
except OSError as ex: |
| 54 |
self.perror(f"Error retrieving size: {ex}") |
| 55 |
return |
| 56 |
|
| 57 |
if args.unit == "KB": |
| 58 |
size //= 1024 |
| 59 |
elif args.unit == "MB": |
| 60 |
size //= 1024 * 1024 |
| 61 |
else: |
| 62 |
args.unit = "bytes" |
| 63 |
size = round(size, 2) |
| 64 |
|
| 65 |
size_str = f"{size:,}" if args.comma else f"{size}" |
| 66 |
self.poutput(f"{size_str} {args.unit}") |
| 67 |
|
| 68 |
|
| 69 |
pow_parser = cmd2.Cmd2ArgumentParser() |
| 70 |
pow_parser.add_argument("base", type=int) |
| 71 |
pow_parser.add_argument("exponent", type=int, choices=range(-5, 6)) |
| 72 |
|
| 73 |
@cmd2.with_argparser(pow_parser) |
| 74 |
@cmd2.with_category(ARGPARSE_USAGE) |
| 75 |
def do_pow(self, args: argparse.Namespace) -> None: |
| 76 |
"""Raise an integer to a small integer exponent, either positive or negative. |
| 77 |
|
| 78 |
:param args: argparse arguments |
| 79 |
""" |
| 80 |
self.poutput(f"{args.base} ** {args.exponent} == {args.base**args.exponent}") |
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
argprint_parser = cmd2.Cmd2ArgumentParser() |
| 85 |
argprint_parser.add_argument("-p", "--piglatin", action="store_true", help="atinLay") |
| 86 |
argprint_parser.add_argument("-s", "--shout", action="store_true", help="N00B EMULATION MODE") |
| 87 |
argprint_parser.add_argument("-r", "--repeat", type=int, help="output [n] times") |
| 88 |
argprint_parser.add_argument("words", nargs="+", help="words to print") |
| 89 |
|
| 90 |
@cmd2.with_argparser(argprint_parser) |
| 91 |
@cmd2.with_category(ARGPARSE_PRINTING) |
| 92 |
def do_print_args(self, args: argparse.Namespace) -> None: |
| 93 |
"""Print the arpgarse argument list this command was called with.""" |
| 94 |
self.poutput(f"print_args was called with the following\n\targuments: {args!r}") |
| 95 |
|
| 96 |
unknownprint_parser = cmd2.Cmd2ArgumentParser() |
| 97 |
unknownprint_parser.add_argument("-p", "--piglatin", action="store_true", help="atinLay") |
| 98 |
unknownprint_parser.add_argument("-s", "--shout", action="store_true", help="N00B EMULATION MODE") |
| 99 |
unknownprint_parser.add_argument("-r", "--repeat", type=int, help="output [n] times") |
| 100 |
|
| 101 |
@cmd2.with_argparser(unknownprint_parser, with_unknown_args=True) |
| 102 |
@cmd2.with_category(ARGPARSE_PRINTING) |
| 103 |
def do_print_unknown(self, args: argparse.Namespace, unknown: list[str]) -> None: |
| 104 |
"""Print the arpgarse argument list this command was called with, including unknown arguments.""" |
| 105 |
self.poutput(f"print_unknown was called with the following arguments\n\tknown: {args!r}\n\tunknown: {unknown}") |
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
calculate_parser = cmd2.Cmd2ArgumentParser(description="Perform simple mathematical calculations.") |
| 111 |
calculate_subparsers = calculate_parser.add_subparsers(title="operation", help="Available operations", required=True) |
| 112 |
|
| 113 |
|
| 114 |
add_description = "Add two numbers" |
| 115 |
add_parser = cmd2.Cmd2ArgumentParser("add", description=add_description) |
| 116 |
add_parser.add_argument("num1", type=int, help="The first number") |
| 117 |
add_parser.add_argument("num2", type=int, help="The second number") |
| 118 |
|
| 119 |
|
| 120 |
subtract_description = "Subtract two numbers" |
| 121 |
subtract_parser = cmd2.Cmd2ArgumentParser("subtract", description=subtract_description) |
| 122 |
subtract_parser.add_argument("num1", type=int, help="The first number") |
| 123 |
subtract_parser.add_argument("num2", type=int, help="The second number") |
| 124 |
|
| 125 |
|
| 126 |
@cmd2.as_subcommand_to("calculate", "add", add_parser, help=add_description.lower()) |
| 127 |
def add(self, args: argparse.Namespace) -> None: |
| 128 |
"""Add subcommand of calculate command.""" |
| 129 |
result = args.num1 + args.num2 |
| 130 |
self.poutput(f"{args.num1} + {args.num2} = {result}") |
| 131 |
|
| 132 |
@cmd2.as_subcommand_to("calculate", "subtract", subtract_parser, help=subtract_description.lower()) |
| 133 |
def subtract(self, args: argparse.Namespace) -> None: |
| 134 |
"""Subtract subcommand of calculate command.""" |
| 135 |
result = args.num1 - args.num2 |
| 136 |
self.poutput(f"{args.num1} - {args.num2} = {result}") |
| 137 |
|
| 138 |
@cmd2.with_argparser(calculate_parser) |
| 139 |
@cmd2.with_category(ARGPARSE_SUBCOMMANDS) |
| 140 |
def do_calculate(self, args: argparse.Namespace) -> None: |
| 141 |
"""Calculate a simple mathematical operation on two integers.""" |
| 142 |
args.cmd2_subcommand_func(args) |
| 143 |
|
| 144 |
|
| 145 |
if __name__ == "__main__": |
| 146 |
import sys |
| 147 |
|
| 148 |
from cmd2.colors import Color |
| 149 |
|
| 150 |
|
| 151 |
parser = cmd2.Cmd2ArgumentParser(description="Process the arguments however you like.") |
| 152 |
|
| 153 |
|
| 154 |
parser.add_argument( |
| 155 |
"-c", |
| 156 |
"--color", |
| 157 |
choices=[Color.RED, Color.ORANGE1, Color.YELLOW, Color.GREEN, Color.BLUE, Color.PURPLE, Color.VIOLET, Color.WHITE], |
| 158 |
help="Color of intro text", |
| 159 |
) |
| 160 |
|
| 161 |
|
| 162 |
args, unknown_args = parser.parse_known_args() |
| 163 |
|
| 164 |
color = Color.WHITE |
| 165 |
if args.color: |
| 166 |
color = args.color |
| 167 |
|
| 168 |
|
| 169 |
sys.argv = sys.argv[:1] + unknown_args |
| 170 |
|
| 171 |
|
| 172 |
app = ArgparsingApp(color) |
| 173 |
|
| 174 |
|
| 175 |
sys.exit(app.cmdloop()) |