summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTodd Leonhardt <todd.leonhardt@gmail.com>2018-09-24 11:13:42 -0400
committerTodd Leonhardt <todd.leonhardt@gmail.com>2018-09-24 11:13:42 -0400
commita2ad70bd79a78123d2bb67b1ff1ed0b815dd721d (patch)
tree22059fc991a5e3ff3b0cc4b4cfc2015efd9dcf41
parent806fe461acee59bcda791a9cb9ebf396af80126e (diff)
downloadcmd2-git-a2ad70bd79a78123d2bb67b1ff1ed0b815dd721d.tar.gz
Added optional color argument to poutput() for providing a color escape code to colorize the output with
Also: - Added optional err_color and war_color arguments to perror() for providing color escape codes - Removed usage of deprecated colorize() method within the examples
-rw-r--r--cmd2/cmd2.py23
-rwxr-xr-xexamples/pirate.py20
-rwxr-xr-xexamples/python_scripting.py4
-rw-r--r--tests/test_cmd2.py9
4 files changed, 39 insertions, 17 deletions
diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py
index b0ff35d4..37033ba4 100644
--- a/cmd2/cmd2.py
+++ b/cmd2/cmd2.py
@@ -561,7 +561,7 @@ class Cmd(cmd.Cmd):
msg = utils.strip_ansi(msg)
fileobj.write(msg)
- def poutput(self, msg: Any, end: str='\n') -> None:
+ def poutput(self, msg: Any, end: str='\n', color: str='') -> None:
"""Smarter self.stdout.write(); color aware and adds newline of not present.
Also handles BrokenPipeError exceptions for when a commands's output has
@@ -569,14 +569,17 @@ class Cmd(cmd.Cmd):
cmd2 command is finished executing.
:param msg: message to print to current stdout (anything convertible to a str with '{}'.format() is OK)
- :param end: string appended after the end of the message if not already present, default a newline
+ :param end: (optional) string appended after the end of the message if not already present, default a newline
+ :param color: (optional) color escape to output this message with
"""
if msg is not None and msg != '':
try:
msg_str = '{}'.format(msg)
- self.decolorized_write(self.stdout, msg_str)
if not msg_str.endswith(end):
- self.decolorized_write(self.stdout, end)
+ msg_str += end
+ if color:
+ msg_str = color + msg_str + Fore.RESET
+ self.decolorized_write(self.stdout, msg_str)
except BrokenPipeError:
# This occurs if a command's output is being piped to another
# process and that process closes before the command is
@@ -586,12 +589,14 @@ class Cmd(cmd.Cmd):
if self.broken_pipe_warning:
sys.stderr.write(self.broken_pipe_warning)
- def perror(self, err: Union[str, Exception], traceback_war: bool=True) -> None:
+ def perror(self, err: Union[str, Exception], traceback_war: bool=True, err_color: str=Fore.LIGHTRED_EX,
+ war_color: str=Fore.LIGHTYELLOW_EX) -> None:
""" Print error message to sys.stderr and if debug is true, print an exception Traceback if one exists.
:param err: an Exception or error message to print out
:param traceback_war: (optional) if True, print a message to let user know they can enable debug
- :return:
+ :param err_color: (optional) color escape to output error with
+ :param war_color: (optional) color escape to output warning with
"""
if self.debug:
import traceback
@@ -601,12 +606,12 @@ class Cmd(cmd.Cmd):
err_msg = "EXCEPTION of type '{}' occurred with message: '{}'\n".format(type(err).__name__, err)
else:
err_msg = "ERROR: {}\n".format(err)
- err_msg = Fore.RED + err_msg + Fore.RESET
+ err_msg = err_color + err_msg + Fore.RESET
self.decolorized_write(sys.stderr, err_msg)
if traceback_war:
war = "To enable full traceback, run the following command: 'set debug true'\n"
- war = Fore.YELLOW + war + Fore.RESET
+ war = war_color + war + Fore.RESET
self.decolorized_write(sys.stderr, war)
def pfeedback(self, msg: str) -> None:
@@ -679,7 +684,7 @@ class Cmd(cmd.Cmd):
except BrokenPipeError:
# This occurs if a command's output is being piped to another process and that process closes before the
# command is finished. If you would like your application to print a warning message, then set the
- # broken_pipe_warning attribute to the message you want printed.
+ # broken_pipe_warning attribute to the message you want printed.`
if self.broken_pipe_warning:
sys.stderr.write(self.broken_pipe_warning)
diff --git a/examples/pirate.py b/examples/pirate.py
index 34906a9f..22274dbf 100755
--- a/examples/pirate.py
+++ b/examples/pirate.py
@@ -8,8 +8,21 @@ It demonstrates many features of cmd2.
"""
import argparse
+from colorama import Fore
+
import cmd2
+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,
+}
+
class Pirate(cmd2.Cmd):
"""A piratical example cmd2 application involving looting and drinking."""
@@ -17,10 +30,10 @@ class Pirate(cmd2.Cmd):
self.default_to_shell = True
self.multiline_commands = ['sing']
self.terminators = self.terminators + ['...']
- self.songcolor = 'blue'
+ self.songcolor = Fore.BLUE
# Add stuff to settable and/or shortcuts before calling base class initializer
- self.settable['songcolor'] = 'Color to ``sing`` in (red/blue/green/cyan/magenta, bold, underline)'
+ self.settable['songcolor'] = 'Color to ``sing`` in (black/red/green/yellow/blue/magenta/cyan/white)'
self.shortcuts.update({'~': 'sing'})
"""Initialize the base class as well as this one"""
@@ -68,7 +81,8 @@ class Pirate(cmd2.Cmd):
def do_sing(self, arg):
"""Sing a colorful song."""
- self.poutput(self.colorize(arg, self.songcolor))
+ color_escape = COLORS.get(self.songcolor, default=Fore.RESET)
+ self.poutput(arg, color=color_escape)
yo_parser = argparse.ArgumentParser()
yo_parser.add_argument('--ho', type=int, default=2, help="How often to chant 'ho'")
diff --git a/examples/python_scripting.py b/examples/python_scripting.py
index ab5ecc2b..b6700cb7 100755
--- a/examples/python_scripting.py
+++ b/examples/python_scripting.py
@@ -17,6 +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
@@ -33,7 +35,7 @@ class CmdLineApp(cmd2.Cmd):
def _set_prompt(self):
"""Set prompt so it displays the current working directory."""
self.cwd = os.getcwd()
- self.prompt = self.colorize('{!r} $ '.format(self.cwd), 'cyan')
+ self.prompt = Fore.CYAN + '{!r} $ '.format(self.cwd) + Fore.RESET
def postcmd(self, stop: bool, line: str) -> bool:
"""Hook method executed just after a command dispatch is finished.
diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py
index 8c8787af..9cb869bd 100644
--- a/tests/test_cmd2.py
+++ b/tests/test_cmd2.py
@@ -1094,18 +1094,19 @@ def test_ansi_prompt_not_esacped(base_app):
def test_ansi_prompt_escaped():
+ from colorama import Fore
app = cmd2.Cmd()
- color = 'cyan'
+ color = Fore.CYAN
prompt = 'InColor'
- color_prompt = app.colorize(prompt, color)
+ color_prompt = color + prompt + Fore.RESET
readline_hack_start = "\x01"
readline_hack_end = "\x02"
readline_safe_prompt = app._surround_ansi_escapes(color_prompt)
assert prompt != color_prompt
- assert readline_safe_prompt.startswith(readline_hack_start + app._colorcodes[color][True] + readline_hack_end)
- assert readline_safe_prompt.endswith(readline_hack_start + app._colorcodes[color][False] + readline_hack_end)
+ assert readline_safe_prompt.startswith(readline_hack_start + color + readline_hack_end)
+ assert readline_safe_prompt.endswith(readline_hack_start + Fore.RESET + readline_hack_end)
class HelpApp(cmd2.Cmd):