diff options
| author | Todd Leonhardt <todd.leonhardt@gmail.com> | 2021-01-31 22:29:57 -0500 |
|---|---|---|
| committer | Todd Leonhardt <todd.leonhardt@gmail.com> | 2021-01-31 22:29:57 -0500 |
| commit | f456b802754c3d1095b488d670bebba21018d823 (patch) | |
| tree | bf7011f585a8a35ab4cc7ff98aaeebed4de87f84 /examples | |
| parent | 918200c02d392c17862fff81bbf58820ed15c725 (diff) | |
| download | cmd2-git-f456b802754c3d1095b488d670bebba21018d823.tar.gz | |
Add black for automatic code format
Diffstat (limited to 'examples')
37 files changed, 253 insertions, 269 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 bd36db29..68da442b 100644 --- a/examples/argparse_completion.py +++ b/examples/argparse_completion.py @@ -41,12 +41,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()] @@ -88,38 +83,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: @@ -129,5 +134,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 a4e02c92..641ff84f 100755 --- a/examples/async_printing.py +++ b/examples/async_printing.py @@ -7,9 +7,7 @@ and changes the window title import random import threading import time -from typing import ( - List, -) +from typing import List import cmd2 from cmd2 import ( @@ -17,17 +15,18 @@ from cmd2 import ( 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): @@ -201,6 +200,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 800a0946..24e6b7d8 100755 --- a/examples/basic.py +++ b/examples/basic.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, + ) 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 83e71a50..aab7d3d1 100755 --- a/examples/basic_completion.py +++ b/examples/basic_completion.py @@ -13,9 +13,7 @@ familiar with argparse. The recommended approach for tab completing positional t argparse-based completion. For an example integrating tab completion with argparse, see argparse_completion.py """ import functools -from typing import ( - List, -) +from typing import List import cmd2 @@ -24,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): @@ -48,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) @@ -71,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) @@ -85,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""" @@ -105,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..951c54b9 100755 --- a/examples/cmd_as_argument.py +++ b/examples/cmd_as_argument.py @@ -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 dc5bdb99..60a75a53 100755 --- a/examples/colors.py +++ b/examples/colors.py @@ -24,9 +24,7 @@ Always regardless of the output destination """ import argparse -from typing import ( - Any, -) +from typing import Any from colorama import ( Back, @@ -35,13 +33,12 @@ from colorama import ( ) import cmd2 -from cmd2 import ( - ansi, -) +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) @@ -106,5 +103,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 194b47b8..6df68bfa 100644 --- a/examples/custom_parser.py +++ b/examples/custom_parser.py @@ -14,6 +14,7 @@ from cmd2 import ( # 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 29fcbd9e..c20a6d4a 100755 --- a/examples/decorator_example.py +++ b/examples/decorator_example.py @@ -11,21 +11,21 @@ all the commands in the transcript against decorator_example.py, verifying that the output produced matches the transcript. """ import argparse -from typing import ( - List, -) +from typing import List 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 diff --git a/examples/default_categories.py b/examples/default_categories.py index efa6729d..0fd485ae 100644 --- a/examples/default_categories.py +++ b/examples/default_categories.py @@ -14,6 +14,7 @@ from cmd2 import ( @with_default_category('Default Category') class MyBaseCommandSet(CommandSet): """Defines a default category for all sub-class CommandSets""" + pass @@ -21,6 +22,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') @@ -34,6 +36,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') @@ -43,6 +46,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') @@ -53,6 +57,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') @@ -62,6 +67,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 35c2cd42..aca370ec 100755 --- a/examples/dynamic_commands.py +++ b/examples/dynamic_commands.py @@ -16,6 +16,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..ffa8d3bf 100755 --- a/examples/example.py +++ b/examples/example.py @@ -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 062ee12d..a35b4df8 100755 --- a/examples/exit_code.py +++ b/examples/exit_code.py @@ -2,9 +2,7 @@ # coding=utf-8 """A simple example demonstrating the following how to emit a non-zero exit code in your cmd2 application. """ -from typing import ( - List, -) +from typing import List import cmd2 @@ -36,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..0b088491 100755 --- a/examples/first_app.py +++ b/examples/first_app.py @@ -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 06303722..19d369da 100755 --- a/examples/hello_cmd2.py +++ b/examples/hello_cmd2.py @@ -3,17 +3,16 @@ """ This is intended to be a completely bare-bones cmd2 application suitable for rapid testing and debugging. """ -from cmd2 import ( - cmd2, -) +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. # 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 0b25375a..16860ec2 100755 --- a/examples/help_categories.py +++ b/examples/help_categories.py @@ -8,9 +8,7 @@ It also demonstrates the effects of decorator order when it comes to argparse er import functools import cmd2 -from cmd2 import ( - COMMAND_NAME, -) +from cmd2 import COMMAND_NAME def my_decorator(f): @@ -18,6 +16,7 @@ def my_decorator(f): def wrapper(*args, **kwds): print('Calling decorated function') return f(*args, **kwds) + return wrapper @@ -72,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) @@ -100,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""" @@ -162,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 8acbf91b..55b43e5d 100755 --- a/examples/hooks.py +++ b/examples/hooks.py @@ -10,9 +10,7 @@ follow a command without any intervening whitespace. """ import re -from typing import ( - List, -) +from typing import List import cmd2 @@ -62,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: @@ -108,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 76a136dd..293d8075 100755 --- a/examples/initialization.py +++ b/examples/initialization.py @@ -24,8 +24,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) @@ -46,8 +50,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 4417bfe5..c3ab41f2 100644 --- a/examples/modular_commands/commandset_basic.py +++ b/examples/modular_commands/commandset_basic.py @@ -2,9 +2,7 @@ """ A simple example demonstrating a loadable command set """ -from typing import ( - List, -) +from typing import List from cmd2 import ( Cmd, @@ -13,9 +11,7 @@ from cmd2 import ( with_category, with_default_category, ) -from cmd2.utils import ( - CompletionError, -) +from cmd2.utils import CompletionError @with_default_category('Basic Completion') @@ -25,14 +21,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 @@ -44,20 +39,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) @@ -67,12 +59,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 4905265a..03bc2507 100644 --- a/examples/modular_commands/commandset_complex.py +++ b/examples/modular_commands/commandset_complex.py @@ -5,14 +5,10 @@ Test CommandSet """ import argparse -from typing import ( - List, -) +from typing import List import cmd2 -from cmd2 import ( - utils, -) +from cmd2 import utils @cmd2.with_default_category('Fruits') @@ -31,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') @@ -43,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_main.py b/examples/modular_commands_main.py index 2c652f22..ae1c64f7 100644 --- a/examples/modular_commands_main.py +++ b/examples/modular_commands_main.py @@ -23,15 +23,9 @@ from cmd2.utils import ( CompletionError, basic_complete, ) -from modular_commands.commandset_basic import ( # noqa: F401 - BasicCompletionCommandSet, -) -from modular_commands.commandset_complex import ( # noqa: F401 - CommandSetA, -) -from modular_commands.commandset_custominit import ( - CustomInitCommandSet, # noqa: F401 -) +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 # Data source for argparse.choices food_item_strs = ['Pizza', 'Ham', 'Ham Sandwich', 'Potato'] @@ -54,12 +48,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()] @@ -101,38 +90,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/override_parser.py b/examples/override_parser.py index b723f6d7..d7d45b82 100755 --- a/examples/override_parser.py +++ b/examples/override_parser.py @@ -13,16 +13,15 @@ import argparse # Next import stuff from cmd2. It will import your module just before the cmd2.Cmd class file is imported # and therefore override the parser class it uses on its commands. -from cmd2 import ( - cmd2, -) +from cmd2 import cmd2 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 191fdd7f..1c323c61 100755 --- a/examples/paged_output.py +++ b/examples/paged_output.py @@ -3,9 +3,7 @@ """A simple example demonstrating the using paged output via the ppaged() method. """ import os -from typing import ( - List, -) +from typing import List import cmd2 @@ -57,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 ab2403be..52e96de2 100755 --- a/examples/pirate.py +++ b/examples/pirate.py @@ -10,13 +10,12 @@ import argparse import cmd2 import cmd2.ansi -from cmd2.constants import ( - MULTILINE_TERMINATOR, -) +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) @@ -90,6 +89,7 @@ class Pirate(cmd2.Cmd): 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 ec138e89..2be7f156 100755 --- a/examples/plumbum_colors.py +++ b/examples/plumbum_colors.py @@ -28,9 +28,7 @@ WARNING: This example requires the plumbum package, which isn't normally require import argparse import cmd2 -from cmd2 import ( - ansi, -) +from cmd2 import ansi from plumbum.colors import ( bg, fg, @@ -75,6 +73,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) diff --git a/examples/python_scripting.py b/examples/python_scripting.py index 5d3f43b3..9465f697 100755 --- a/examples/python_scripting.py +++ b/examples/python_scripting.py @@ -24,9 +24,7 @@ import argparse import os import cmd2 -from cmd2 import ( - ansi, -) +from cmd2 import ansi class CmdLineApp(cmd2.Cmd): @@ -120,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 a290f5df..bd955580 100755 --- a/examples/table_creation.py +++ b/examples/table_creation.py @@ -8,9 +8,7 @@ from typing import ( List, ) -from cmd2 import ( - ansi, -) +from cmd2 import ansi from cmd2.table_creator import ( AlternatingTable, BorderedTable, @@ -22,6 +20,7 @@ from cmd2.table_creator import ( 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 @@ -39,27 +38,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): |
