diff options
author | Todd Leonhardt <todd.leonhardt@gmail.com> | 2019-06-27 23:54:07 -0400 |
---|---|---|
committer | Todd Leonhardt <todd.leonhardt@gmail.com> | 2019-06-27 23:54:07 -0400 |
commit | f91ccf2bb28531f9d1dee551314cb091fa57df74 (patch) | |
tree | c4f2571eda21f4b2d636545f0f89a8835aa057fd /examples | |
parent | 00388938d2c02922660e63ae163373b25789fafa (diff) | |
download | cmd2-git-f91ccf2bb28531f9d1dee551314cb091fa57df74.tar.gz |
Simplified ansi color dictionaries and lookup methods
Also:
- Updated examples that use color to use cmd2.ansi instead of colorama
- Updated tests that use color to use cmd2.ansi instead of colorama
- plumbum_colorspy example shows how to override color lookup functions to use a different color library
Diffstat (limited to 'examples')
-rwxr-xr-x | examples/async_printing.py | 26 | ||||
-rwxr-xr-x | examples/colors.py | 92 | ||||
-rwxr-xr-x | examples/plumbum_colors.py | 84 | ||||
-rwxr-xr-x | examples/python_scripting.py | 5 | ||||
-rwxr-xr-x | examples/table_display.py | 3 |
5 files changed, 47 insertions, 163 deletions
diff --git a/examples/async_printing.py b/examples/async_printing.py index 3089070f..b3618475 100755 --- a/examples/async_printing.py +++ b/examples/async_printing.py @@ -4,15 +4,13 @@ A simple example demonstrating an application that asynchronously prints alerts, updates the prompt and changes the window title """ - import random import threading import time from typing import List -from colorama import Fore - import cmd2 +from cmd2 import ansi ALERTS = ["Watch as this application prints alerts and updates the prompt", "This will only happen when the prompt is present", @@ -141,26 +139,12 @@ class AlerterApp(cmd2.Cmd): return alert_str def _generate_colored_prompt(self) -> str: - """ - Randomly generates a colored prompt + """Randomly generates a colored prompt :return: the new prompt """ - rand_num = random.randint(1, 20) - - status_color = Fore.RESET - - if rand_num == 1: - status_color = Fore.LIGHTRED_EX - elif rand_num == 2: - status_color = Fore.LIGHTYELLOW_EX - elif rand_num == 3: - status_color = Fore.CYAN - elif rand_num == 4: - status_color = Fore.LIGHTGREEN_EX - elif rand_num == 5: - status_color = Fore.LIGHTBLUE_EX - - return status_color + self.visible_prompt + Fore.RESET + fg_color = random.choice(list(ansi.FG_COLORS.keys())) + bg_color = random.choice(list(ansi.BG_COLORS.keys())) + return ansi.style(self.visible_prompt, fg=fg_color, bg=bg_color) def _alerter_thread_func(self) -> None: """ Prints alerts and updates the prompt any time the prompt is showing """ diff --git a/examples/colors.py b/examples/colors.py index f8a9dfdb..c0c221c8 100755 --- a/examples/colors.py +++ b/examples/colors.py @@ -6,7 +6,7 @@ A sample application for cmd2. Demonstrating colorized output. Experiment with the command line options on the `speak` command to see how different output colors ca -The colors setting has three possible values: +The allow_ansi setting has three possible values: Never poutput(), pfeedback(), and ppaged() strip all ANSI escape sequences @@ -16,68 +16,38 @@ Terminal (the default value) poutput(), pfeedback(), and ppaged() do not strip any ANSI escape sequences when the output is a terminal, but if the output is a pipe or a file the escape sequences are stripped. If you want colorized - output you must add ANSI escape sequences, preferably using some python - color library like `plumbum.colors`, `colorama`, `blessings`, or - `termcolor`. + output you must add ANSI escape sequences using either cmd2's internal ansi + module or another color library such as `plumbum.colors` or `colorama`. Always poutput(), pfeedback(), and ppaged() never strip ANSI escape sequences, regardless of the output destination """ - -import random import argparse import cmd2 -from colorama import Fore, Back - -FG_COLORS = { - 'black': Fore.BLACK, - 'red': Fore.RED, - 'green': Fore.GREEN, - 'yellow': Fore.YELLOW, - 'blue': Fore.BLUE, - 'magenta': Fore.MAGENTA, - 'cyan': Fore.CYAN, - 'white': Fore.WHITE, -} -BG_COLORS = { - 'black': Back.BLACK, - 'red': Back.RED, - 'green': Back.GREEN, - 'yellow': Back.YELLOW, - 'blue': Back.BLUE, - 'magenta': Back.MAGENTA, - 'cyan': Back.CYAN, - 'white': Back.WHITE, -} +from cmd2 import ansi class CmdLineApp(cmd2.Cmd): """Example cmd2 application demonstrating colorized output.""" - - # Setting this true makes it run a shell command if a cmd2/cmd command doesn't exist - # default_to_shell = True - MUMBLES = ['like', '...', 'um', 'er', 'hmmm', 'ahh'] - MUMBLE_FIRST = ['so', 'like', 'well'] - MUMBLE_LAST = ['right?'] - def __init__(self): - 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=True, multiline_commands=['orate'], shortcuts=shortcuts) + super().__init__(use_ipython=True) self.maxrepeats = 3 # Make maxrepeats settable at runtime self.settable['maxrepeats'] = 'max repetitions for speak command' + # Should ANSI color output be allowed + self.allow_ansi = ansi.ANSI_TERMINAL + speak_parser = argparse.ArgumentParser() speak_parser.add_argument('-p', '--piglatin', action='store_true', help='atinLay') speak_parser.add_argument('-s', '--shout', action='store_true', help='N00B EMULATION MODE') speak_parser.add_argument('-r', '--repeat', type=int, help='output [n] times') - speak_parser.add_argument('-f', '--fg', choices=FG_COLORS, help='foreground color to apply to output') - speak_parser.add_argument('-b', '--bg', choices=BG_COLORS, help='background color to apply to output') + speak_parser.add_argument('-f', '--fg', choices=ansi.FG_COLORS, help='foreground color to apply to output') + speak_parser.add_argument('-b', '--bg', choices=ansi.BG_COLORS, help='background color to apply to output') speak_parser.add_argument('words', nargs='+', help='words to say') @cmd2.with_argparser(speak_parser) @@ -92,49 +62,11 @@ class CmdLineApp(cmd2.Cmd): words.append(word) repetitions = args.repeat or 1 - - color_on = '' - if args.fg: - color_on += FG_COLORS[args.fg] - if args.bg: - color_on += BG_COLORS[args.bg] - color_off = Fore.RESET + Back.RESET + output_str = ansi.style(' '.join(words), fg=args.fg, bg=args.bg) for i in range(min(repetitions, self.maxrepeats)): # .poutput handles newlines, and accommodates output redirection too - self.poutput(color_on + ' '.join(words) + color_off) - - do_say = do_speak # now "say" is a synonym for "speak" - do_orate = do_speak # another synonym, but this one takes multi-line input - - mumble_parser = argparse.ArgumentParser() - mumble_parser.add_argument('-r', '--repeat', type=int, help='how many times to repeat') - mumble_parser.add_argument('-f', '--fg', help='foreground color to apply to output') - mumble_parser.add_argument('-b', '--bg', help='background color to apply to output') - mumble_parser.add_argument('words', nargs='+', help='words to say') - - @cmd2.with_argparser(mumble_parser) - def do_mumble(self, args): - """Mumbles what you tell me to.""" - color_on = '' - if args.fg and args.fg in FG_COLORS: - color_on += FG_COLORS[args.fg] - if args.bg and args.bg in BG_COLORS: - color_on += BG_COLORS[args.bg] - color_off = Fore.RESET + Back.RESET - - repetitions = args.repeat or 1 - for i in range(min(repetitions, self.maxrepeats)): - output = [] - if random.random() < .33: - output.append(random.choice(self.MUMBLE_FIRST)) - for word in args.words: - if random.random() < .40: - output.append(random.choice(self.MUMBLES)) - output.append(word) - if random.random() < .25: - output.append(random.choice(self.MUMBLE_LAST)) - self.poutput(color_on + ' '.join(output) + color_off) + self.poutput(output_str) if __name__ == '__main__': diff --git a/examples/plumbum_colors.py b/examples/plumbum_colors.py index 2c57c22b..971029fa 100755 --- a/examples/plumbum_colors.py +++ b/examples/plumbum_colors.py @@ -6,7 +6,7 @@ A sample application for cmd2. Demonstrating colorized output using the plumbum Experiment with the command line options on the `speak` command to see how different output colors ca -The colors setting has three possible values: +The allow_ansi setting has three possible values: Never poutput(), pfeedback(), and ppaged() strip all ANSI escape sequences @@ -16,9 +16,8 @@ Terminal (the default value) poutput(), pfeedback(), and ppaged() do not strip any ANSI escape sequences when the output is a terminal, but if the output is a pipe or a file the escape sequences are stripped. If you want colorized - output you must add ANSI escape sequences, preferably using some python - color library like `plumbum.colors`, `colorama`, `blessings`, or - `termcolor`. + output you must add ANSI escape sequences using either cmd2's internal ansi + module or another color library such as `plumbum.colors` or `colorama`. Always poutput(), pfeedback(), and ppaged() never strip ANSI escape sequences, @@ -26,13 +25,11 @@ Always WARNING: This example requires the plumbum package, which isn't normally required by cmd2. """ - -import random import argparse import cmd2 -from colorama import Fore, Back -from plumbum.colors import fg, bg, reset +from cmd2 import ansi +from plumbum.colors import fg, bg FG_COLORS = { 'black': fg.Black, @@ -43,7 +40,9 @@ FG_COLORS = { 'magenta': fg.Purple, 'cyan': fg.SkyBlue1, 'white': fg.White, + 'purple': fg.Purple, } + BG_COLORS = { 'black': bg.BLACK, 'red': bg.DarkRedA, @@ -56,25 +55,31 @@ BG_COLORS = { } -class CmdLineApp(cmd2.Cmd): - """Example cmd2 application demonstrating colorized output.""" +def get_fg(fg): + return str(FG_COLORS[fg]) + + +def get_bg(bg): + return str(BG_COLORS[bg]) + + +ansi.fg_lookup = get_fg +ansi.bg_lookup = get_bg - # Setting this true makes it run a shell command if a cmd2/cmd command doesn't exist - # default_to_shell = True - MUMBLES = ['like', '...', 'um', 'er', 'hmmm', 'ahh'] - MUMBLE_FIRST = ['so', 'like', 'well'] - MUMBLE_LAST = ['right?'] +class CmdLineApp(cmd2.Cmd): + """Example cmd2 application demonstrating colorized output.""" def __init__(self): - 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=True, multiline_commands=['orate'], shortcuts=shortcuts) + super().__init__(use_ipython=True) self.maxrepeats = 3 # Make maxrepeats settable at runtime self.settable['maxrepeats'] = 'max repetitions for speak command' + # Should ANSI color output be allowed + self.allow_ansi = ansi.ANSI_TERMINAL + speak_parser = argparse.ArgumentParser() speak_parser.add_argument('-p', '--piglatin', action='store_true', help='atinLay') speak_parser.add_argument('-s', '--shout', action='store_true', help='N00B EMULATION MODE') @@ -95,52 +100,15 @@ class CmdLineApp(cmd2.Cmd): words.append(word) repetitions = args.repeat or 1 - - color_on = '' - if args.fg: - color_on += FG_COLORS[args.fg] - if args.bg: - color_on += BG_COLORS[args.bg] - color_off = reset + output_str = ansi.style(' '.join(words), fg=args.fg, bg=args.bg) for i in range(min(repetitions, self.maxrepeats)): # .poutput handles newlines, and accommodates output redirection too - self.poutput(color_on + ' '.join(words) + color_off) - - do_say = do_speak # now "say" is a synonym for "speak" - do_orate = do_speak # another synonym, but this one takes multi-line input - - mumble_parser = argparse.ArgumentParser() - mumble_parser.add_argument('-r', '--repeat', type=int, help='how many times to repeat') - mumble_parser.add_argument('-f', '--fg', help='foreground color to apply to output') - mumble_parser.add_argument('-b', '--bg', help='background color to apply to output') - mumble_parser.add_argument('words', nargs='+', help='words to say') - - @cmd2.with_argparser(mumble_parser) - def do_mumble(self, args): - """Mumbles what you tell me to.""" - color_on = '' - if args.fg and args.fg in FG_COLORS: - color_on += FG_COLORS[args.fg] - if args.bg and args.bg in BG_COLORS: - color_on += BG_COLORS[args.bg] - color_off = Fore.RESET + Back.RESET - - repetitions = args.repeat or 1 - for i in range(min(repetitions, self.maxrepeats)): - output = [] - if random.random() < .33: - output.append(random.choice(self.MUMBLE_FIRST)) - for word in args.words: - if random.random() < .40: - output.append(random.choice(self.MUMBLES)) - output.append(word) - if random.random() < .25: - output.append(random.choice(self.MUMBLE_LAST)) - self.poutput(color_on + ' '.join(output) + color_off) + self.poutput(output_str) if __name__ == '__main__': import sys + c = CmdLineApp() sys.exit(c.cmdloop()) diff --git a/examples/python_scripting.py b/examples/python_scripting.py index 0cbfddff..3d0a54a9 100755 --- a/examples/python_scripting.py +++ b/examples/python_scripting.py @@ -17,9 +17,8 @@ This application and the "scripts/conditional.py" script serve as an example for import argparse import os -from colorama import Fore - import cmd2 +from cmd2 import ansi class CmdLineApp(cmd2.Cmd): @@ -35,7 +34,7 @@ class CmdLineApp(cmd2.Cmd): def _set_prompt(self): """Set prompt so it displays the current working directory.""" self.cwd = os.getcwd() - self.prompt = Fore.CYAN + '{!r} $ '.format(self.cwd) + Fore.RESET + self.prompt = ansi.style('{!r} $ '.format(self.cwd), fg='cyan') def postcmd(self, stop: bool, line: str) -> bool: """Hook method executed just after a command dispatch is finished. diff --git a/examples/table_display.py b/examples/table_display.py index dcde7a81..cedd2ca0 100755 --- a/examples/table_display.py +++ b/examples/table_display.py @@ -9,7 +9,8 @@ You can use the arrow keys (left, right, up, and down) to scroll around the tabl You can quit out of the pager by typing "q". You can also search for text within the pager using "/". WARNING: This example requires the tableformatter module: https://github.com/python-tableformatter/tableformatter -- pip install tableformatter +and either the colored or colorama module +- pip install tableformatter colorama """ from typing import Tuple |