diff options
Diffstat (limited to 'examples')
40 files changed, 248 insertions, 217 deletions
diff --git a/examples/alias_startup.py b/examples/alias_startup.py index 3fa9ec5a..3ddcc2fe 100755 --- a/examples/alias_startup.py +++ b/examples/alias_startup.py @@ -23,5 +23,6 @@ class AliasAndStartup(cmd2.Cmd): if __name__ == '__main__': import sys + app = AliasAndStartup() sys.exit(app.cmdloop()) diff --git a/examples/arg_decorators.py b/examples/arg_decorators.py index a085341d..f4d92624 100755 --- a/examples/arg_decorators.py +++ b/examples/arg_decorators.py @@ -14,11 +14,9 @@ class ArgparsingApp(cmd2.Cmd): # do_fsize parser fsize_parser = cmd2.Cmd2ArgumentParser(description='Obtain the size of a file') - fsize_parser.add_argument('-c', '--comma', action='store_true', - help='add comma for thousands separator') + fsize_parser.add_argument('-c', '--comma', action='store_true', help='add comma for thousands separator') fsize_parser.add_argument('-u', '--unit', choices=['MB', 'KB'], help='unit to display size in') - fsize_parser.add_argument('file_path', help='path of file', - completer_method=cmd2.Cmd.path_complete) + fsize_parser.add_argument('file_path', help='path of file', completer_method=cmd2.Cmd.path_complete) @cmd2.with_argparser(fsize_parser) def do_fsize(self, args: argparse.Namespace) -> None: diff --git a/examples/arg_print.py b/examples/arg_print.py index dbf740ff..6736c74f 100755 --- a/examples/arg_print.py +++ b/examples/arg_print.py @@ -64,5 +64,6 @@ class ArgumentAndOptionPrinter(cmd2.Cmd): if __name__ == '__main__': import sys + app = ArgumentAndOptionPrinter() sys.exit(app.cmdloop()) diff --git a/examples/argparse_completion.py b/examples/argparse_completion.py index e44533b3..39904dec 100644 --- a/examples/argparse_completion.py +++ b/examples/argparse_completion.py @@ -30,12 +30,7 @@ def completer_function(text: str, line: str, begidx: int, endidx: int) -> List[s def choices_completion_item() -> List[CompletionItem]: """Return CompletionItem instead of strings. These give more context to what's being tab completed.""" - items = \ - { - 1: "My item", - 2: "Another item", - 3: "Yet another item" - } + items = {1: "My item", 2: "Another item", 3: "Yet another item"} return [CompletionItem(item_id, description) for item_id, description in items.items()] @@ -77,38 +72,48 @@ class ArgparseCompletion(Cmd): raise CompletionError("debug must be true") # Parser for example command - example_parser = Cmd2ArgumentParser(description="Command demonstrating tab completion with argparse\n" - "Notice even the flags of this command tab complete") + example_parser = Cmd2ArgumentParser( + description="Command demonstrating tab completion with argparse\n" "Notice even the flags of this command tab complete" + ) # Tab complete from a list using argparse choices. Set metavar if you don't # want the entire choices list showing in the usage text for this command. - example_parser.add_argument('--choices', choices=food_item_strs, metavar="CHOICE", - help="tab complete using choices") + example_parser.add_argument('--choices', choices=food_item_strs, metavar="CHOICE", help="tab complete using choices") # Tab complete from choices provided by a choices function and choices method - example_parser.add_argument('--choices_function', choices_function=choices_function, - help="tab complete using a choices_function") - example_parser.add_argument('--choices_method', choices_method=choices_method, - help="tab complete using a choices_method") + example_parser.add_argument( + '--choices_function', choices_function=choices_function, help="tab complete using a choices_function" + ) + example_parser.add_argument('--choices_method', choices_method=choices_method, help="tab complete using a choices_method") # Tab complete using a completer function and completer method - example_parser.add_argument('--completer_function', completer_function=completer_function, - help="tab complete using a completer_function") - example_parser.add_argument('--completer_method', completer_method=Cmd.path_complete, - help="tab complete using a completer_method") + example_parser.add_argument( + '--completer_function', completer_function=completer_function, help="tab complete using a completer_function" + ) + example_parser.add_argument( + '--completer_method', completer_method=Cmd.path_complete, help="tab complete using a completer_method" + ) # Demonstrate raising a CompletionError while tab completing - example_parser.add_argument('--completion_error', choices_method=choices_completion_error, - help="raise a CompletionError while tab completing if debug is False") + example_parser.add_argument( + '--completion_error', + choices_method=choices_completion_error, + help="raise a CompletionError while tab completing if debug is False", + ) # Demonstrate returning CompletionItems instead of strings - example_parser.add_argument('--completion_item', choices_function=choices_completion_item, metavar="ITEM_ID", - descriptive_header="Description", - help="demonstrate use of CompletionItems") + example_parser.add_argument( + '--completion_item', + choices_function=choices_completion_item, + metavar="ITEM_ID", + descriptive_header="Description", + help="demonstrate use of CompletionItems", + ) # Demonstrate use of arg_tokens dictionary - example_parser.add_argument('--arg_tokens', choices_function=choices_arg_tokens, - help="demonstrate use of arg_tokens dictionary") + example_parser.add_argument( + '--arg_tokens', choices_function=choices_arg_tokens, help="demonstrate use of arg_tokens dictionary" + ) @with_argparser(example_parser) def do_example(self, _: argparse.Namespace) -> None: @@ -118,5 +123,6 @@ class ArgparseCompletion(Cmd): if __name__ == '__main__': import sys + app = ArgparseCompletion() sys.exit(app.cmdloop()) diff --git a/examples/async_printing.py b/examples/async_printing.py index a136d8e2..d7304661 100755 --- a/examples/async_printing.py +++ b/examples/async_printing.py @@ -12,17 +12,18 @@ from typing import List import cmd2 from cmd2 import fg, style -ALERTS = ["Watch as this application prints alerts and updates the prompt", - "This will only happen when the prompt is present", - "Notice how it doesn't interfere with your typing or cursor location", - "Go ahead and type some stuff and move the cursor throughout the line", - "Keep typing...", - "Move that cursor...", - "Pretty seamless, eh?", - "Feedback can also be given in the window title. Notice the alert count up there?", - "You can stop and start the alerts by typing stop_alerts and start_alerts", - "This demo will now continue to print alerts at random intervals" - ] +ALERTS = [ + "Watch as this application prints alerts and updates the prompt", + "This will only happen when the prompt is present", + "Notice how it doesn't interfere with your typing or cursor location", + "Go ahead and type some stuff and move the cursor throughout the line", + "Keep typing...", + "Move that cursor...", + "Pretty seamless, eh?", + "Feedback can also be given in the window title. Notice the alert count up there?", + "You can stop and start the alerts by typing stop_alerts and start_alerts", + "This demo will now continue to print alerts at random intervals", +] class AlerterApp(cmd2.Cmd): @@ -196,6 +197,7 @@ class AlerterApp(cmd2.Cmd): if __name__ == '__main__': import sys + app = AlerterApp() app.set_window_title("Asynchronous Printer Test") sys.exit(app.cmdloop()) diff --git a/examples/basic.py b/examples/basic.py index 2a1e9a12..3d703950 100755 --- a/examples/basic.py +++ b/examples/basic.py @@ -16,8 +16,12 @@ class BasicApp(cmd2.Cmd): CUSTOM_CATEGORY = 'My Custom Commands' def __init__(self): - super().__init__(multiline_commands=['echo'], persistent_history_file='cmd2_history.dat', - startup_script='scripts/startup.txt', use_ipython=True) + super().__init__( + multiline_commands=['echo'], + persistent_history_file='cmd2_history.dat', + startup_script='scripts/startup.txt', + use_ipython=True, + ) self.intro = style('Welcome to PyOhio 2019 and cmd2!', fg=fg.red, bg=bg.white, bold=True) + ' π' diff --git a/examples/basic_completion.py b/examples/basic_completion.py index f33029c9..aab7d3d1 100755 --- a/examples/basic_completion.py +++ b/examples/basic_completion.py @@ -22,14 +22,13 @@ food_item_strs = ['Pizza', 'Ham', 'Ham Sandwich', 'Potato'] sport_item_strs = ['Bat', 'Basket', 'Basketball', 'Football', 'Space Ball'] # This data is used to demonstrate delimiter_complete -file_strs = \ - [ - '/home/user/file.db', - '/home/user/file space.db', - '/home/user/another.db', - '/home/other user/maps.db', - '/home/other user/tests.db' - ] +file_strs = [ + '/home/user/file.db', + '/home/user/file space.db', + '/home/user/another.db', + '/home/other user/maps.db', + '/home/other user/tests.db', +] class BasicCompletion(cmd2.Cmd): @@ -46,20 +45,17 @@ class BasicCompletion(cmd2.Cmd): def complete_flag_based(self, text, line, begidx, endidx) -> List[str]: """Completion function for do_flag_based""" - flag_dict = \ - { - # Tab complete food items after -f and --food flags in command line - '-f': food_item_strs, - '--food': food_item_strs, - - # Tab complete sport items after -s and --sport flags in command line - '-s': sport_item_strs, - '--sport': sport_item_strs, - - # Tab complete using path_complete function after -p and --path flags in command line - '-p': self.path_complete, - '--path': self.path_complete, - } + flag_dict = { + # Tab complete food items after -f and --food flags in command line + '-f': food_item_strs, + '--food': food_item_strs, + # Tab complete sport items after -s and --sport flags in command line + '-s': sport_item_strs, + '--sport': sport_item_strs, + # Tab complete using path_complete function after -p and --path flags in command line + '-p': self.path_complete, + '--path': self.path_complete, + } return self.flag_based_complete(text, line, begidx, endidx, flag_dict=flag_dict) @@ -69,12 +65,11 @@ class BasicCompletion(cmd2.Cmd): def complete_index_based(self, text, line, begidx, endidx) -> List[str]: """Completion function for do_index_based""" - index_dict = \ - { - 1: food_item_strs, # Tab complete food items at index 1 in command line - 2: sport_item_strs, # Tab complete sport items at index 2 in command line - 3: self.path_complete, # Tab complete using path_complete function at index 3 in command line - } + index_dict = { + 1: food_item_strs, # Tab complete food items at index 1 in command line + 2: sport_item_strs, # Tab complete sport items at index 2 in command line + 3: self.path_complete, # Tab complete using path_complete function at index 3 in command line + } return self.index_based_complete(text, line, begidx, endidx, index_dict=index_dict) @@ -83,8 +78,7 @@ class BasicCompletion(cmd2.Cmd): self.poutput("Args: {}".format(statement.args)) # Use a partialmethod to set arguments to delimiter_complete - complete_delimiter_complete = functools.partialmethod(cmd2.Cmd.delimiter_complete, - match_against=file_strs, delimiter='/') + complete_delimiter_complete = functools.partialmethod(cmd2.Cmd.delimiter_complete, match_against=file_strs, delimiter='/') def do_raise_error(self, statement: cmd2.Statement): """Demonstrates effect of raising CompletionError""" @@ -103,5 +97,6 @@ class BasicCompletion(cmd2.Cmd): if __name__ == '__main__': import sys + app = BasicCompletion() sys.exit(app.cmdloop()) diff --git a/examples/cmd_as_argument.py b/examples/cmd_as_argument.py index b65bcbcb..73f0dc22 100755 --- a/examples/cmd_as_argument.py +++ b/examples/cmd_as_argument.py @@ -50,7 +50,7 @@ class CmdLineApp(cmd2.Cmd): words = [] for word in args.words: if args.piglatin: - word = '%s%say' % (word[1:], word[0]) + word = '{}{}ay'.format(word[1:], word[0]) if args.shout: word = word.upper() words.append(word) @@ -72,13 +72,13 @@ class CmdLineApp(cmd2.Cmd): repetitions = args.repeat or 1 for i in range(min(repetitions, self.maxrepeats)): output = [] - if random.random() < .33: + if random.random() < 0.33: output.append(random.choice(self.MUMBLE_FIRST)) for word in args.words: - if random.random() < .40: + if random.random() < 0.40: output.append(random.choice(self.MUMBLES)) output.append(word) - if random.random() < .25: + if random.random() < 0.25: output.append(random.choice(self.MUMBLE_LAST)) self.poutput(' '.join(output)) @@ -86,15 +86,11 @@ class CmdLineApp(cmd2.Cmd): def main(argv=None): """Run when invoked from the operating system shell""" - parser = argparse.ArgumentParser( - description='Commands as arguments' - ) + parser = argparse.ArgumentParser(description='Commands as arguments') command_help = 'optional command to run, if no command given, enter an interactive shell' - parser.add_argument('command', nargs='?', - help=command_help) + parser.add_argument('command', nargs='?', help=command_help) arg_help = 'optional arguments for command' - parser.add_argument('command_args', nargs=argparse.REMAINDER, - help=arg_help) + parser.add_argument('command_args', nargs=argparse.REMAINDER, help=arg_help) args = parser.parse_args(argv) @@ -113,4 +109,5 @@ def main(argv=None): if __name__ == '__main__': import sys + sys.exit(main()) diff --git a/examples/colors.py b/examples/colors.py index 8f8e3c6e..9d02c166 100755 --- a/examples/colors.py +++ b/examples/colors.py @@ -34,6 +34,7 @@ from cmd2 import ansi class CmdLineApp(cmd2.Cmd): """Example cmd2 application demonstrating colorized output.""" + def __init__(self): # Set use_ipython to True to enable the "ipy" command which embeds and interactive IPython shell super().__init__(use_ipython=True) @@ -61,7 +62,7 @@ class CmdLineApp(cmd2.Cmd): words = [] for word in args.words: if args.piglatin: - word = '%s%say' % (word[1:], word[0]) + word = '{}{}ay'.format(word[1:], word[0]) if args.shout: word = word.upper() words.append(word) @@ -98,5 +99,6 @@ class CmdLineApp(cmd2.Cmd): if __name__ == '__main__': import sys + c = CmdLineApp() sys.exit(c.cmdloop()) diff --git a/examples/custom_parser.py b/examples/custom_parser.py index 34c7bee2..fa21a0b4 100644 --- a/examples/custom_parser.py +++ b/examples/custom_parser.py @@ -10,6 +10,7 @@ from cmd2 import Cmd2ArgumentParser, ansi, set_default_argument_parser # First define the parser class CustomParser(Cmd2ArgumentParser): """Overrides error class""" + def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) diff --git a/examples/decorator_example.py b/examples/decorator_example.py index 1b6d7570..d661eeba 100755 --- a/examples/decorator_example.py +++ b/examples/decorator_example.py @@ -18,12 +18,14 @@ import cmd2 class CmdLineApp(cmd2.Cmd): """ Example cmd2 application. """ + def __init__(self, ip_addr=None, port=None, transcript_files=None): shortcuts = dict(cmd2.DEFAULT_SHORTCUTS) shortcuts.update({'&': 'speak'}) # Set use_ipython to True to enable the "ipy" command which embeds and interactive IPython shell - super().__init__(use_ipython=False, transcript_files=transcript_files, multiline_commands=['orate'], - shortcuts=shortcuts) + super().__init__( + use_ipython=False, transcript_files=transcript_files, multiline_commands=['orate'], shortcuts=shortcuts + ) self.maxrepeats = 3 # Make maxrepeats settable at runtime @@ -48,7 +50,7 @@ class CmdLineApp(cmd2.Cmd): words = [] for word in args.words: if args.piglatin: - word = '%s%say' % (word[1:], word[0]) + word = '{}{}ay'.format(word[1:], word[0]) if args.shout: word = word.upper() words.append(word) diff --git a/examples/default_categories.py b/examples/default_categories.py index 19699513..bee2b1ea 100644 --- a/examples/default_categories.py +++ b/examples/default_categories.py @@ -11,6 +11,7 @@ from cmd2 import CommandSet, with_default_category @with_default_category('Default Category') class MyBaseCommandSet(CommandSet): """Defines a default category for all sub-class CommandSets""" + pass @@ -18,6 +19,7 @@ class ChildInheritsParentCategories(MyBaseCommandSet): """ This subclass doesn't declare any categories so all commands here are also categorized under 'Default Category' """ + def do_hello(self, _: cmd2.Statement): self._cmd.poutput('Hello') @@ -31,6 +33,7 @@ class ChildOverridesParentCategoriesNonHeritable(MyBaseCommandSet): This subclass overrides the 'Default Category' from the parent, but in a non-heritable fashion. Sub-classes of this CommandSet will not inherit this category and will, instead, inherit 'Default Category' """ + def do_goodbye(self, _: cmd2.Statement): self._cmd.poutput('Goodbye') @@ -40,6 +43,7 @@ class GrandchildInheritsGrandparentCategory(ChildOverridesParentCategoriesNonHer This subclass's parent class declared its default category non-heritable. Instead, it inherits the category defined by the grandparent class. """ + def do_aloha(self, _: cmd2.Statement): self._cmd.poutput('Aloha') @@ -50,6 +54,7 @@ class ChildOverridesParentCategories(MyBaseCommandSet): This subclass is decorated with a default category that is heritable. This overrides the parent class's default category declaration. """ + def do_bonjour(self, _: cmd2.Statement): self._cmd.poutput('Bonjour') @@ -59,6 +64,7 @@ class GrandchildInheritsHeritable(ChildOverridesParentCategories): This subclass's parent declares a default category that overrides its parent. As a result, commands in this CommandSet will be categorized under 'Heritable Category' """ + def do_monde(self, _: cmd2.Statement): self._cmd.poutput('Monde') diff --git a/examples/dynamic_commands.py b/examples/dynamic_commands.py index 620acb7f..4fc2629f 100755 --- a/examples/dynamic_commands.py +++ b/examples/dynamic_commands.py @@ -13,6 +13,7 @@ CATEGORY = 'Dynamic Commands' class CommandsInLoop(cmd2.Cmd): """Example of dynamically adding do_* commands.""" + def __init__(self): # Add dynamic commands before calling cmd2.Cmd's init since it validates command names for command in COMMAND_LIST: diff --git a/examples/environment.py b/examples/environment.py index 670b63ac..5f5d927b 100755 --- a/examples/environment.py +++ b/examples/environment.py @@ -13,11 +13,7 @@ class EnvironmentApp(cmd2.Cmd): super().__init__() self.degrees_c = 22 self.sunny = False - self.add_settable(cmd2.Settable('degrees_c', - int, - 'Temperature in Celsius', - onchange_cb=self._onchange_degrees_c - )) + self.add_settable(cmd2.Settable('degrees_c', int, 'Temperature in Celsius', onchange_cb=self._onchange_degrees_c)) self.add_settable(cmd2.Settable('sunny', bool, 'Is it sunny outside?')) def do_sunbathe(self, arg): @@ -38,5 +34,6 @@ class EnvironmentApp(cmd2.Cmd): if __name__ == '__main__': import sys + c = EnvironmentApp() sys.exit(c.cmdloop()) diff --git a/examples/event_loops.py b/examples/event_loops.py index 53d3ca2b..86dc01fb 100755 --- a/examples/event_loops.py +++ b/examples/event_loops.py @@ -11,6 +11,7 @@ import cmd2 class Cmd2EventBased(cmd2.Cmd): """Basic example of how to run cmd2 without it controlling the main loop.""" + def __init__(self): super().__init__() diff --git a/examples/example.py b/examples/example.py index 0272a6e5..daa07eee 100755 --- a/examples/example.py +++ b/examples/example.py @@ -46,7 +46,7 @@ class CmdLineApp(cmd2.Cmd): words = [] for word in args.words: if args.piglatin: - word = '%s%say' % (word[1:], word[0]) + word = '{}{}ay'.format(word[1:], word[0]) if args.shout: word = word.upper() words.append(word) @@ -68,18 +68,19 @@ class CmdLineApp(cmd2.Cmd): repetitions = args.repeat or 1 for _ in range(min(repetitions, self.maxrepeats)): output = [] - if random.random() < .33: + if random.random() < 0.33: output.append(random.choice(self.MUMBLE_FIRST)) for word in args.words: - if random.random() < .40: + if random.random() < 0.40: output.append(random.choice(self.MUMBLES)) output.append(word) - if random.random() < .25: + if random.random() < 0.25: output.append(random.choice(self.MUMBLE_LAST)) self.poutput(' '.join(output)) if __name__ == '__main__': import sys + c = CmdLineApp() sys.exit(c.cmdloop()) diff --git a/examples/exit_code.py b/examples/exit_code.py index 89ed86cd..a35b4df8 100755 --- a/examples/exit_code.py +++ b/examples/exit_code.py @@ -34,6 +34,7 @@ Usage: exit [exit_code] if __name__ == '__main__': import sys + app = ReplWithExitCode() sys_exit_code = app.cmdloop() app.poutput('{!r} exiting with code: {}'.format(sys.argv[0], sys_exit_code)) diff --git a/examples/first_app.py b/examples/first_app.py index d8272e86..3330b459 100755 --- a/examples/first_app.py +++ b/examples/first_app.py @@ -41,7 +41,7 @@ class FirstApp(cmd2.Cmd): words = [] for word in args.words: if args.piglatin: - word = '%s%say' % (word[1:], word[0]) + word = '{}{}ay'.format(word[1:], word[0]) if args.shout: word = word.upper() words.append(word) @@ -56,5 +56,6 @@ class FirstApp(cmd2.Cmd): if __name__ == '__main__': import sys + c = FirstApp() sys.exit(c.cmdloop()) diff --git a/examples/hello_cmd2.py b/examples/hello_cmd2.py index 94ec334f..7bd0ef2c 100755 --- a/examples/hello_cmd2.py +++ b/examples/hello_cmd2.py @@ -7,11 +7,11 @@ from cmd2 import cmd2 if __name__ == '__main__': import sys - # If run as the main application, simply start a bare-bones cmd2 application with only built-in functionality. + # If run as the main application, simply start a bare-bones cmd2 application with only built-in functionality. # Set "use_ipython" to True to include the ipy command if IPython is installed, which supports advanced interactive # debugging of your application via introspection on self. app = cmd2.Cmd(use_ipython=True, persistent_history_file='cmd2_history.dat') - app.self_in_py = True # Enable access to "self" within the py command - app.debug = True # Show traceback if/when an exception occurs + app.self_in_py = True # Enable access to "self" within the py command + app.debug = True # Show traceback if/when an exception occurs sys.exit(app.cmdloop()) diff --git a/examples/help_categories.py b/examples/help_categories.py index 7401bafe..16860ec2 100755 --- a/examples/help_categories.py +++ b/examples/help_categories.py @@ -16,6 +16,7 @@ def my_decorator(f): def wrapper(*args, **kwds): print('Calling decorated function') return f(*args, **kwds) + return wrapper @@ -70,8 +71,9 @@ class HelpCategories(cmd2.Cmd): """Redeploy command""" self.poutput('Redeploy') - restart_parser = cmd2.DEFAULT_ARGUMENT_PARSER(description='Restart', - epilog='my_decorator does not run when argparse errors') + restart_parser = cmd2.DEFAULT_ARGUMENT_PARSER( + description='Restart', epilog='my_decorator does not run when argparse errors' + ) restart_parser.add_argument('when', choices=START_TIMES, help='Specify when to restart') @cmd2.with_argparser(restart_parser) @@ -98,15 +100,10 @@ class HelpCategories(cmd2.Cmd): self.poutput('Find Leakers') # Tag the above command functions under the category Application Management - cmd2.categorize((do_list, - do_deploy, - do_start, - do_sessions, - do_redeploy, - do_expire, - do_undeploy, - do_stop, - do_findleakers), CMD_CAT_APP_MGMT) + cmd2.categorize( + (do_list, do_deploy, do_start, do_sessions, do_redeploy, do_expire, do_undeploy, do_stop, do_findleakers), + CMD_CAT_APP_MGMT, + ) def do_resources(self, _): """Resources command""" @@ -160,8 +157,7 @@ class HelpCategories(cmd2.Cmd): @cmd2.with_category("Command Management") def do_disable_commands(self, _): """Disable the Application Management commands""" - message_to_print = "{} is not available while {} commands are disabled".format(COMMAND_NAME, - self.CMD_CAT_APP_MGMT) + message_to_print = "{} is not available while {} commands are disabled".format(COMMAND_NAME, self.CMD_CAT_APP_MGMT) self.disable_category(self.CMD_CAT_APP_MGMT, message_to_print) self.poutput("The Application Management commands have been disabled") diff --git a/examples/hooks.py b/examples/hooks.py index f8079e58..55b43e5d 100755 --- a/examples/hooks.py +++ b/examples/hooks.py @@ -60,20 +60,17 @@ class CmdLineApp(cmd2.Cmd): command_pattern = re.compile(r'^([^\s\d]+)(\d+)') match = command_pattern.search(command) if match: - data.statement = self.statement_parser.parse("{} {} {}".format( - match.group(1), - match.group(2), - '' if data.statement.args is None else data.statement.args - )) + data.statement = self.statement_parser.parse( + "{} {} {}".format(match.group(1), match.group(2), '' if data.statement.args is None else data.statement.args) + ) return data def downcase_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData: """A hook to make uppercase commands lowercase.""" command = data.statement.command.lower() - data.statement = self.statement_parser.parse("{} {}".format( - command, - '' if data.statement.args is None else data.statement.args - )) + data.statement = self.statement_parser.parse( + "{} {}".format(command, '' if data.statement.args is None else data.statement.args) + ) return data def abbrev_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData: @@ -106,5 +103,6 @@ class CmdLineApp(cmd2.Cmd): if __name__ == '__main__': import sys + c = CmdLineApp() sys.exit(c.cmdloop()) diff --git a/examples/initialization.py b/examples/initialization.py index 50bb73aa..6137c6a7 100755 --- a/examples/initialization.py +++ b/examples/initialization.py @@ -20,8 +20,12 @@ class BasicApp(cmd2.Cmd): CUSTOM_CATEGORY = 'My Custom Commands' def __init__(self): - super().__init__(multiline_commands=['echo'], persistent_history_file='cmd2_history.dat', - startup_script='scripts/startup.txt', use_ipython=True) + super().__init__( + multiline_commands=['echo'], + persistent_history_file='cmd2_history.dat', + startup_script='scripts/startup.txt', + use_ipython=True, + ) # Prints an intro banner once upon application startup self.intro = style('Welcome to cmd2!', fg=fg.red, bg=bg.white, bold=True) @@ -42,8 +46,9 @@ class BasicApp(cmd2.Cmd): self.foreground_color = 'cyan' # Make echo_fg settable at runtime - self.add_settable(cmd2.Settable('foreground_color', str, 'Foreground color to use with echo command', - choices=fg.colors())) + self.add_settable( + cmd2.Settable('foreground_color', str, 'Foreground color to use with echo command', choices=fg.colors()) + ) @cmd2.with_category(CUSTOM_CATEGORY) def do_intro(self, _): diff --git a/examples/migrating.py b/examples/migrating.py index 86a59ed6..e7c2f19e 100755 --- a/examples/migrating.py +++ b/examples/migrating.py @@ -31,18 +31,19 @@ class CmdLineApp(cmd.Cmd): """Mumbles what you tell me to.""" words = line.split(' ') output = [] - if random.random() < .33: + if random.random() < 0.33: output.append(random.choice(self.MUMBLE_FIRST)) for word in words: - if random.random() < .40: + if random.random() < 0.40: output.append(random.choice(self.MUMBLES)) output.append(word) - if random.random() < .25: + if random.random() < 0.25: output.append(random.choice(self.MUMBLE_LAST)) print(' '.join(output), file=self.stdout) if __name__ == '__main__': import sys + c = CmdLineApp() sys.exit(c.cmdloop()) diff --git a/examples/modular_commands/commandset_basic.py b/examples/modular_commands/commandset_basic.py index 2ceda439..cb1b07bc 100644 --- a/examples/modular_commands/commandset_basic.py +++ b/examples/modular_commands/commandset_basic.py @@ -15,14 +15,13 @@ class BasicCompletionCommandSet(CommandSet): sport_item_strs = ['Bat', 'Basket', 'Basketball', 'Football', 'Space Ball'] # This data is used to demonstrate delimiter_complete - file_strs = \ - [ - '/home/user/file.db', - '/home/user/file space.db', - '/home/user/another.db', - '/home/other user/maps.db', - '/home/other user/tests.db' - ] + file_strs = [ + '/home/user/file.db', + '/home/user/file space.db', + '/home/user/another.db', + '/home/other user/maps.db', + '/home/other user/tests.db', + ] def do_flag_based(self, cmd: Cmd, statement: Statement): """Tab completes arguments based on a preceding flag using flag_based_complete @@ -34,20 +33,17 @@ class BasicCompletionCommandSet(CommandSet): def complete_flag_based(self, cmd: Cmd, text: str, line: str, begidx: int, endidx: int) -> List[str]: """Completion function for do_flag_based""" - flag_dict = \ - { - # Tab complete food items after -f and --food flags in command line - '-f': self.food_item_strs, - '--food': self.food_item_strs, - - # Tab complete sport items after -s and --sport flags in command line - '-s': self.sport_item_strs, - '--sport': self.sport_item_strs, - - # Tab complete using path_complete function after -p and --path flags in command line - '-p': cmd.path_complete, - '--path': cmd.path_complete, - } + flag_dict = { + # Tab complete food items after -f and --food flags in command line + '-f': self.food_item_strs, + '--food': self.food_item_strs, + # Tab complete sport items after -s and --sport flags in command line + '-s': self.sport_item_strs, + '--sport': self.sport_item_strs, + # Tab complete using path_complete function after -p and --path flags in command line + '-p': cmd.path_complete, + '--path': cmd.path_complete, + } return cmd.flag_based_complete(text, line, begidx, endidx, flag_dict=flag_dict) @@ -57,12 +53,11 @@ class BasicCompletionCommandSet(CommandSet): def complete_index_based(self, cmd: Cmd, text: str, line: str, begidx: int, endidx: int) -> List[str]: """Completion function for do_index_based""" - index_dict = \ - { - 1: self.food_item_strs, # Tab complete food items at index 1 in command line - 2: self.sport_item_strs, # Tab complete sport items at index 2 in command line - 3: cmd.path_complete, # Tab complete using path_complete function at index 3 in command line - } + index_dict = { + 1: self.food_item_strs, # Tab complete food items at index 1 in command line + 2: self.sport_item_strs, # Tab complete sport items at index 2 in command line + 3: cmd.path_complete, # Tab complete using path_complete function at index 3 in command line + } return cmd.index_based_complete(text, line, begidx, endidx, index_dict=index_dict) diff --git a/examples/modular_commands/commandset_complex.py b/examples/modular_commands/commandset_complex.py index 579c0677..03bc2507 100644 --- a/examples/modular_commands/commandset_complex.py +++ b/examples/modular_commands/commandset_complex.py @@ -27,9 +27,8 @@ class CommandSetA(cmd2.CommandSet): def do_cranberry(self, ns: argparse.Namespace, unknown: List[str]): self._cmd.poutput('Cranberry {}!!'.format(ns.arg1)) if unknown and len(unknown): - self._cmd.poutput('Unknown: ' + ', '.join(['{}']*len(unknown)).format(*unknown)) - self._cmd.last_result = {'arg1': ns.arg1, - 'unknown': unknown} + self._cmd.poutput('Unknown: ' + ', '.join(['{}'] * len(unknown)).format(*unknown)) + self._cmd.last_result = {'arg1': ns.arg1, 'unknown': unknown} def help_cranberry(self): self._cmd.stdout.write('This command does diddly squat...\n') @@ -39,7 +38,7 @@ class CommandSetA(cmd2.CommandSet): def do_durian(self, args: List[str]): """Durian Command""" self._cmd.poutput('{} Arguments: '.format(len(args))) - self._cmd.poutput(', '.join(['{}']*len(args)).format(*args)) + self._cmd.poutput(', '.join(['{}'] * len(args)).format(*args)) def complete_durian(self, text: str, line: str, begidx: int, endidx: int) -> List[str]: return utils.basic_complete(text, line, begidx, endidx, ['stinks', 'smells', 'disgusting']) diff --git a/examples/modular_commands_dynamic.py b/examples/modular_commands_dynamic.py index b2be5dd1..86a74d4b 100644 --- a/examples/modular_commands_dynamic.py +++ b/examples/modular_commands_dynamic.py @@ -10,6 +10,7 @@ on which CommandSets are loaded """ import argparse + import cmd2 from cmd2 import CommandSet, with_argparser, with_category, with_default_category diff --git a/examples/modular_commands_main.py b/examples/modular_commands_main.py index b698e00f..34837481 100644 --- a/examples/modular_commands_main.py +++ b/examples/modular_commands_main.py @@ -7,12 +7,13 @@ with examples of how to integrate tab completion with argparse-based commands. import argparse from typing import Dict, Iterable, List, Optional -from cmd2 import Cmd, Cmd2ArgumentParser, CommandSet, CompletionItem, with_argparser -from cmd2.utils import CompletionError, basic_complete from modular_commands.commandset_basic import BasicCompletionCommandSet # noqa: F401 from modular_commands.commandset_complex import CommandSetA # noqa: F401 from modular_commands.commandset_custominit import CustomInitCommandSet # noqa: F401 +from cmd2 import Cmd, Cmd2ArgumentParser, CommandSet, CompletionItem, with_argparser +from cmd2.utils import CompletionError, basic_complete + # Data source for argparse.choices food_item_strs = ['Pizza', 'Ham', 'Ham Sandwich', 'Potato'] @@ -34,12 +35,7 @@ def completer_function(text: str, line: str, begidx: int, endidx: int) -> List[s def choices_completion_item() -> List[CompletionItem]: """Return CompletionItem instead of strings. These give more context to what's being tab completed.""" - items = \ - { - 1: "My item", - 2: "Another item", - 3: "Yet another item" - } + items = {1: "My item", 2: "Another item", 3: "Yet another item"} return [CompletionItem(item_id, description) for item_id, description in items.items()] @@ -81,38 +77,48 @@ class WithCommandSets(Cmd): raise CompletionError("debug must be true") # Parser for example command - example_parser = Cmd2ArgumentParser(description="Command demonstrating tab completion with argparse\n" - "Notice even the flags of this command tab complete") + example_parser = Cmd2ArgumentParser( + description="Command demonstrating tab completion with argparse\n" "Notice even the flags of this command tab complete" + ) # Tab complete from a list using argparse choices. Set metavar if you don't # want the entire choices list showing in the usage text for this command. - example_parser.add_argument('--choices', choices=food_item_strs, metavar="CHOICE", - help="tab complete using choices") + example_parser.add_argument('--choices', choices=food_item_strs, metavar="CHOICE", help="tab complete using choices") # Tab complete from choices provided by a choices function and choices method - example_parser.add_argument('--choices_function', choices_function=choices_function, - help="tab complete using a choices_function") - example_parser.add_argument('--choices_method', choices_method=choices_method, - help="tab complete using a choices_method") + example_parser.add_argument( + '--choices_function', choices_function=choices_function, help="tab complete using a choices_function" + ) + example_parser.add_argument('--choices_method', choices_method=choices_method, help="tab complete using a choices_method") # Tab complete using a completer function and completer method - example_parser.add_argument('--completer_function', completer_function=completer_function, - help="tab complete using a completer_function") - example_parser.add_argument('--completer_method', completer_method=Cmd.path_complete, - help="tab complete using a completer_method") + example_parser.add_argument( + '--completer_function', completer_function=completer_function, help="tab complete using a completer_function" + ) + example_parser.add_argument( + '--completer_method', completer_method=Cmd.path_complete, help="tab complete using a completer_method" + ) # Demonstrate raising a CompletionError while tab completing - example_parser.add_argument('--completion_error', choices_method=choices_completion_error, - help="raise a CompletionError while tab completing if debug is False") + example_parser.add_argument( + '--completion_error', + choices_method=choices_completion_error, + help="raise a CompletionError while tab completing if debug is False", + ) # Demonstrate returning CompletionItems instead of strings - example_parser.add_argument('--completion_item', choices_function=choices_completion_item, metavar="ITEM_ID", - descriptive_header="Description", - help="demonstrate use of CompletionItems") + example_parser.add_argument( + '--completion_item', + choices_function=choices_completion_item, + metavar="ITEM_ID", + descriptive_header="Description", + help="demonstrate use of CompletionItems", + ) # Demonstrate use of arg_tokens dictionary - example_parser.add_argument('--arg_tokens', choices_function=choices_arg_tokens, - help="demonstrate use of arg_tokens dictionary") + example_parser.add_argument( + '--arg_tokens', choices_function=choices_arg_tokens, help="demonstrate use of arg_tokens dictionary" + ) @with_argparser(example_parser) def do_example(self, _: argparse.Namespace) -> None: diff --git a/examples/modular_subcommands.py b/examples/modular_subcommands.py index c1d499f0..d3c16198 100644 --- a/examples/modular_subcommands.py +++ b/examples/modular_subcommands.py @@ -11,6 +11,7 @@ The `load` and `unload` command will load and unload the CommandSets. The availa subcommands to the `cut` command will change depending on which CommandSets are loaded. """ import argparse + import cmd2 from cmd2 import CommandSet, with_argparser, with_category, with_default_category diff --git a/examples/override_parser.py b/examples/override_parser.py index b6548388..d7d45b82 100755 --- a/examples/override_parser.py +++ b/examples/override_parser.py @@ -20,7 +20,8 @@ argparse.cmd2_parser_module = 'examples.custom_parser' if __name__ == '__main__': import sys + app = cmd2.Cmd(use_ipython=True, persistent_history_file='cmd2_history.dat') - app.self_in_py = True # Enable access to "self" within the py command - app.debug = True # Show traceback if/when an exception occurs + app.self_in_py = True # Enable access to "self" within the py command + app.debug = True # Show traceback if/when an exception occurs sys.exit(app.cmdloop()) diff --git a/examples/paged_output.py b/examples/paged_output.py index cba5c7c5..1c323c61 100755 --- a/examples/paged_output.py +++ b/examples/paged_output.py @@ -55,5 +55,6 @@ class PagedOutput(cmd2.Cmd): if __name__ == '__main__': import sys + app = PagedOutput() sys.exit(app.cmdloop()) diff --git a/examples/persistent_history.py b/examples/persistent_history.py index bc62cb14..330e3537 100755 --- a/examples/persistent_history.py +++ b/examples/persistent_history.py @@ -10,6 +10,7 @@ import cmd2 class Cmd2PersistentHistory(cmd2.Cmd): """Basic example of how to enable persistent readline history within your cmd2 app.""" + def __init__(self, hist_file): """Configure the app to load persistent history from a file (both readline and cmd2 history command affected). diff --git a/examples/pirate.py b/examples/pirate.py index a50f9a51..ba5bc7d5 100755 --- a/examples/pirate.py +++ b/examples/pirate.py @@ -15,6 +15,7 @@ from cmd2.constants import MULTILINE_TERMINATOR class Pirate(cmd2.Cmd): """A piratical example cmd2 application involving looting and drinking.""" + def __init__(self): """Initialize the base class as well as this one""" shortcuts = dict(cmd2.DEFAULT_SHORTCUTS) @@ -40,7 +41,7 @@ class Pirate(cmd2.Cmd): def postcmd(self, stop, line): """Runs right before a command is about to return.""" if self.gold != self.initial_gold: - self.poutput('Now we gots {0} doubloons'.format(self.gold)) + self.poutput('Now we gots {} doubloons'.format(self.gold)) if self.gold < 0: self.poutput("Off to debtorrr's prison.") self.exit_code = -1 @@ -60,7 +61,7 @@ class Pirate(cmd2.Cmd): self.gold -= int(arg) except ValueError: if arg: - self.poutput('''What's "{0}"? I'll take rrrum.'''.format(arg)) + self.poutput('''What's "{}"? I'll take rrrum.'''.format(arg)) self.gold -= 1 def do_quit(self, arg): @@ -83,11 +84,12 @@ class Pirate(cmd2.Cmd): chant = ['yo'] + ['ho'] * args.ho separator = ', ' if args.commas else ' ' chant = separator.join(chant) - self.poutput('{0} and a bottle of {1}'.format(chant, args.beverage)) + self.poutput('{} and a bottle of {}'.format(chant, args.beverage)) if __name__ == '__main__': import sys + # Create an instance of the Pirate derived class and enter the REPL with cmdloop(). pirate = Pirate() sys_exit_code = pirate.cmdloop() diff --git a/examples/plumbum_colors.py b/examples/plumbum_colors.py index a30e4c70..8784aa40 100755 --- a/examples/plumbum_colors.py +++ b/examples/plumbum_colors.py @@ -27,9 +27,10 @@ WARNING: This example requires the plumbum package, which isn't normally require """ import argparse +from plumbum.colors import bg, fg + import cmd2 from cmd2 import ansi -from plumbum.colors import bg, fg class FgColors(ansi.ColorBase): @@ -70,6 +71,7 @@ ansi.bg_lookup = get_bg class CmdLineApp(cmd2.Cmd): """Example cmd2 application demonstrating colorized output.""" + def __init__(self): # Set use_ipython to True to enable the "ipy" command which embeds and interactive IPython shell super().__init__(use_ipython=True) @@ -97,7 +99,7 @@ class CmdLineApp(cmd2.Cmd): words = [] for word in args.words: if args.piglatin: - word = '%s%say' % (word[1:], word[0]) + word = '{}{}ay'.format(word[1:], word[0]) if args.shout: word = word.upper() words.append(word) diff --git a/examples/python_scripting.py b/examples/python_scripting.py index 6e4295d4..9465f697 100755 --- a/examples/python_scripting.py +++ b/examples/python_scripting.py @@ -118,5 +118,6 @@ class CmdLineApp(cmd2.Cmd): if __name__ == '__main__': import sys + c = CmdLineApp() sys.exit(c.cmdloop()) diff --git a/examples/remove_builtin_commands.py b/examples/remove_builtin_commands.py index 4c1794d6..b0b19447 100755 --- a/examples/remove_builtin_commands.py +++ b/examples/remove_builtin_commands.py @@ -27,5 +27,6 @@ class RemoveBuiltinCommands(cmd2.Cmd): if __name__ == '__main__': import sys + app = RemoveBuiltinCommands() sys.exit(app.cmdloop()) diff --git a/examples/remove_settable.py b/examples/remove_settable.py index 6a2e4062..a7b87126 100755 --- a/examples/remove_settable.py +++ b/examples/remove_settable.py @@ -7,7 +7,6 @@ import cmd2 class MyApp(cmd2.Cmd): - def __init__(self): super().__init__() self.remove_settable('debug') @@ -15,5 +14,6 @@ class MyApp(cmd2.Cmd): if __name__ == '__main__': import sys + c = MyApp() sys.exit(c.cmdloop()) diff --git a/examples/scripts/arg_printer.py b/examples/scripts/arg_printer.py index f5f30c6d..924e269a 100755 --- a/examples/scripts/arg_printer.py +++ b/examples/scripts/arg_printer.py @@ -3,7 +3,6 @@ import os import sys -print("Running Python script {!r} which was called with {} arguments".format(os.path.basename(sys.argv[0]), - len(sys.argv) - 1)) +print("Running Python script {!r} which was called with {} arguments".format(os.path.basename(sys.argv[0]), len(sys.argv) - 1)) for i, arg in enumerate(sys.argv[1:]): print("arg {}: {!r}".format(i + 1, arg)) diff --git a/examples/subcommands.py b/examples/subcommands.py index dd69d97e..56c91b14 100755 --- a/examples/subcommands.py +++ b/examples/subcommands.py @@ -68,6 +68,7 @@ class SubcommandsExample(cmd2.Cmd): Example cmd2 application where we a base command which has a couple subcommands and the "sport" subcommand has tab completion enabled. """ + def __init__(self): super().__init__() @@ -114,5 +115,6 @@ class SubcommandsExample(cmd2.Cmd): if __name__ == '__main__': import sys + app = SubcommandsExample() sys.exit(app.cmdloop()) diff --git a/examples/table_creation.py b/examples/table_creation.py index 6325b200..e199afdc 100755 --- a/examples/table_creation.py +++ b/examples/table_creation.py @@ -11,6 +11,7 @@ from cmd2.table_creator import AlternatingTable, BorderedTable, Column, Horizont class DollarFormatter: """Example class to show that any object type can be passed as data to TableCreator and converted to a string""" + def __init__(self, val: float) -> None: self.val = val @@ -28,27 +29,28 @@ green = functools.partial(ansi.style, fg=ansi.fg.green) columns: List[Column] = list() columns.append(Column("Name", width=20)) columns.append(Column("Address", width=38)) -columns.append(Column("Income", width=14, - header_horiz_align=HorizontalAlignment.RIGHT, - data_horiz_align=HorizontalAlignment.RIGHT)) +columns.append( + Column("Income", width=14, header_horiz_align=HorizontalAlignment.RIGHT, data_horiz_align=HorizontalAlignment.RIGHT) +) # Table data which demonstrates handling of wrapping and text styles data_list: List[List[Any]] = list() -data_list.append(["Billy Smith", - "123 Sesame St.\n" - "Fake Town, USA 33445", DollarFormatter(100333.03)]) -data_list.append(["William Longfellow Marmaduke III", - "984 Really Long Street Name Which Will Wrap Nicely\n" - "Apt 22G\n" - "Pensacola, FL 32501", DollarFormatter(55135.22)]) -data_list.append(["James " + blue("Bluestone"), - bold_yellow("This address has line feeds,\n" - "text styles, and wrapping. ") + blue("Style is preserved across lines."), - DollarFormatter(300876.10)]) -data_list.append(["John Jones", - "9235 Highway 32\n" - + green("Greenville") + ", SC 29604", - DollarFormatter(82987.71)]) +data_list.append(["Billy Smith", "123 Sesame St.\n" "Fake Town, USA 33445", DollarFormatter(100333.03)]) +data_list.append( + [ + "William Longfellow Marmaduke III", + "984 Really Long Street Name Which Will Wrap Nicely\n" "Apt 22G\n" "Pensacola, FL 32501", + DollarFormatter(55135.22), + ] +) +data_list.append( + [ + "James " + blue("Bluestone"), + bold_yellow("This address has line feeds,\n" "text styles, and wrapping. ") + blue("Style is preserved across lines."), + DollarFormatter(300876.10), + ] +) +data_list.append(["John Jones", "9235 Highway 32\n" + green("Greenville") + ", SC 29604", DollarFormatter(82987.71)]) def ansi_print(text): diff --git a/examples/unicode_commands.py b/examples/unicode_commands.py index 0a7c5ac7..df02b028 100755 --- a/examples/unicode_commands.py +++ b/examples/unicode_commands.py @@ -16,7 +16,7 @@ class UnicodeApp(cmd2.Cmd): def do_πprint(self, _): """This command prints π to 5 decimal places.""" - self.poutput("π = {0:.6}".format(math.pi)) + self.poutput("π = {:.6}".format(math.pi)) def do_δ½ ε₯½(self, arg): """This command says hello in Chinese (Mandarin).""" |