summaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
Diffstat (limited to 'examples')
-rw-r--r--examples/argparse_completion.py2
-rwxr-xr-xexamples/async_printing.py14
-rwxr-xr-xexamples/basic.py6
-rwxr-xr-xexamples/colors.py46
-rwxr-xr-xexamples/initialization.py14
-rwxr-xr-xexamples/pirate.py10
-rwxr-xr-xexamples/plumbum_colors.py123
-rwxr-xr-xexamples/table_creation.py9
8 files changed, 44 insertions, 180 deletions
diff --git a/examples/argparse_completion.py b/examples/argparse_completion.py
index 7350f46c..f67b0b7b 100644
--- a/examples/argparse_completion.py
+++ b/examples/argparse_completion.py
@@ -47,7 +47,7 @@ class ArgparseCompletion(Cmd):
def choices_completion_item(self) -> List[CompletionItem]:
"""Return CompletionItem instead of strings. These give more context to what's being tab completed."""
fancy_item = "These things can\ncontain newlines and\n"
- fancy_item += ansi.style("styled text!!", fg=ansi.fg.bright_yellow, underline=True)
+ fancy_item += ansi.style("styled text!!", fg=ansi.StdFg.LIGHT_YELLOW, underline=True)
items = {1: "My item", 2: "Another item", 3: "Yet another item", 4: fancy_item}
return [CompletionItem(item_id, description) for item_id, description in items.items()]
diff --git a/examples/async_printing.py b/examples/async_printing.py
index 4832bf0a..fa6cad2a 100755
--- a/examples/async_printing.py
+++ b/examples/async_printing.py
@@ -13,7 +13,7 @@ from typing import (
import cmd2
from cmd2 import (
- fg,
+ StdFg,
style,
)
@@ -151,18 +151,18 @@ class AlerterApp(cmd2.Cmd):
"""
rand_num = random.randint(1, 20)
- status_color = fg.reset
+ status_color = StdFg.RESET
if rand_num == 1:
- status_color = fg.bright_red
+ status_color = StdFg.LIGHT_RED
elif rand_num == 2:
- status_color = fg.bright_yellow
+ status_color = StdFg.LIGHT_YELLOW
elif rand_num == 3:
- status_color = fg.cyan
+ status_color = StdFg.CYAN
elif rand_num == 4:
- status_color = fg.bright_green
+ status_color = StdFg.LIGHT_GREEN
elif rand_num == 5:
- status_color = fg.bright_blue
+ status_color = StdFg.LIGHT_BLUE
return style(self.visible_prompt, fg=status_color)
diff --git a/examples/basic.py b/examples/basic.py
index 8f507e03..167dee80 100755
--- a/examples/basic.py
+++ b/examples/basic.py
@@ -10,8 +10,8 @@
"""
import cmd2
from cmd2 import (
- bg,
- fg,
+ StdBg,
+ StdFg,
style,
)
@@ -27,7 +27,7 @@ class BasicApp(cmd2.Cmd):
include_ipy=True,
)
- self.intro = style('Welcome to PyOhio 2019 and cmd2!', fg=fg.red, bg=bg.white, bold=True) + ' 😀'
+ self.intro = style('Welcome to PyOhio 2019 and cmd2!', fg=StdFg.RED, bg=StdBg.WHITE, bold=True) + ' 😀'
# Allow access to your application in py and ipy via self
self.self_in_py = True
diff --git a/examples/colors.py b/examples/colors.py
index 24a5cf09..589cd607 100755
--- a/examples/colors.py
+++ b/examples/colors.py
@@ -16,28 +16,23 @@ Terminal
(the default value) poutput(), pfeedback(), and ppaged() do not strip any
ANSI style sequences when the output is a terminal, but if the output is
a pipe or a file the style sequences are stripped. If you want colorized
- output you must add ANSI style sequences using either cmd2's internal ansi
- module or another color library such as `plumbum.colors` or `colorama`.
+ output, add ANSI style sequences using cmd2's internal ansi module.
Always
poutput(), pfeedback(), and ppaged() never strip ANSI style sequences,
regardless of the output destination
"""
-from typing import (
- Any,
-)
-
-from colorama import (
- Back,
- Fore,
- Style,
-)
import cmd2
from cmd2 import (
+ StdBg,
+ StdFg,
ansi,
)
+fg_choices = [c.name.lower() for c in StdFg]
+bg_choices = [c.name.lower() for c in StdBg]
+
class CmdLineApp(cmd2.Cmd):
"""Example cmd2 application demonstrating colorized output."""
@@ -51,14 +46,14 @@ class CmdLineApp(cmd2.Cmd):
self.add_settable(cmd2.Settable('maxrepeats', int, 'max repetitions for speak command', self))
# Should ANSI color output be allowed
- self.allow_style = ansi.STYLE_TERMINAL
+ self.allow_style = ansi.AllowStyle.TERMINAL
speak_parser = cmd2.Cmd2ArgumentParser()
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=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('-f', '--fg', choices=fg_choices, help='foreground color to apply to output')
+ speak_parser.add_argument('-b', '--bg', choices=bg_choices, help='background color to apply to output')
speak_parser.add_argument('-l', '--bold', action='store_true', help='bold the output')
speak_parser.add_argument('-u', '--underline', action='store_true', help='underline the output')
speak_parser.add_argument('words', nargs='+', help='words to say')
@@ -75,29 +70,14 @@ class CmdLineApp(cmd2.Cmd):
words.append(word)
repetitions = args.repeat or 1
- output_str = ansi.style(' '.join(words), fg=args.fg, bg=args.bg, bold=args.bold, underline=args.underline)
+
+ fg_color = StdFg[args.fg.upper()] if args.fg else None
+ bg_color = StdBg[args.bg.upper()] if args.bg else None
+ output_str = ansi.style(' '.join(words), fg=fg_color, bg=bg_color, bold=args.bold, underline=args.underline)
for _ in range(min(repetitions, self.maxrepeats)):
# .poutput handles newlines, and accommodates output redirection too
self.poutput(output_str)
- self.perror('error message at the end')
-
- # noinspection PyMethodMayBeStatic
- def perror(self, msg: Any = '', *, end: str = '\n', apply_style: bool = True) -> None:
- """Override perror() method from `cmd2.Cmd`
-
- Use colorama native approach for styling the text instead of `cmd2.ansi` methods
-
- :param msg: message to print (anything convertible to a str with '{}'.format() is OK)
- :param end: string appended after the end of the message, default a newline
- :param apply_style: If True, then ansi.style_error will be applied to the message text. Set to False in cases
- where the message text already has the desired style. Defaults to True.
- """
- if apply_style:
- final_msg = "{}{}{}{}".format(Fore.RED, Back.YELLOW, msg, Style.RESET_ALL)
- else:
- final_msg = "{}".format(msg)
- ansi.style_aware_write(sys.stderr, final_msg + end)
def do_timetravel(self, _):
"""A command which always generates an error message, to demonstrate custom error colors"""
diff --git a/examples/initialization.py b/examples/initialization.py
index dfea2183..375711ff 100755
--- a/examples/initialization.py
+++ b/examples/initialization.py
@@ -14,8 +14,8 @@
"""
import cmd2
from cmd2 import (
- bg,
- fg,
+ StdBg,
+ StdFg,
style,
)
@@ -32,7 +32,7 @@ class BasicApp(cmd2.Cmd):
)
# Prints an intro banner once upon application startup
- self.intro = style('Welcome to cmd2!', fg=fg.red, bg=bg.white, bold=True)
+ self.intro = style('Welcome to cmd2!', fg=StdFg.RED, bg=StdBg.WHITE, bold=True)
# Show this as the prompt when asking for input
self.prompt = 'myapp> '
@@ -47,11 +47,12 @@ class BasicApp(cmd2.Cmd):
self.default_category = 'cmd2 Built-in Commands'
# Color to output text in with echo command
- self.foreground_color = 'cyan'
+ self.foreground_color = StdFg.CYAN.name.lower()
# Make echo_fg settable at runtime
+ fg_colors = [c.name.lower() for c in StdFg]
self.add_settable(
- cmd2.Settable('foreground_color', str, 'Foreground color to use with echo command', self, choices=fg.colors())
+ cmd2.Settable('foreground_color', str, 'Foreground color to use with echo command', self, choices=fg_colors)
)
@cmd2.with_category(CUSTOM_CATEGORY)
@@ -62,7 +63,8 @@ class BasicApp(cmd2.Cmd):
@cmd2.with_category(CUSTOM_CATEGORY)
def do_echo(self, arg):
"""Example of a multiline command"""
- self.poutput(style(arg, fg=self.foreground_color))
+ fg_color = StdFg[self.foreground_color.upper()]
+ self.poutput(style(arg, fg=fg_color))
if __name__ == '__main__':
diff --git a/examples/pirate.py b/examples/pirate.py
index 2de832eb..437ee07b 100755
--- a/examples/pirate.py
+++ b/examples/pirate.py
@@ -8,11 +8,15 @@ It demonstrates many features of cmd2.
"""
import cmd2
-import cmd2.ansi
+from cmd2 import (
+ StdFg,
+)
from cmd2.constants import (
MULTILINE_TERMINATOR,
)
+color_choices = [c.name.lower() for c in StdFg]
+
class Pirate(cmd2.Cmd):
"""A piratical example cmd2 application involving looting and drinking."""
@@ -27,7 +31,7 @@ class Pirate(cmd2.Cmd):
self.songcolor = 'blue'
# Make songcolor settable at runtime
- self.add_settable(cmd2.Settable('songcolor', str, 'Color to ``sing``', self, choices=cmd2.ansi.fg.colors()))
+ self.add_settable(cmd2.Settable('songcolor', str, 'Color to ``sing``', self, choices=color_choices))
# prompts and defaults
self.gold = 0
@@ -72,7 +76,7 @@ class Pirate(cmd2.Cmd):
def do_sing(self, arg):
"""Sing a colorful song."""
- self.poutput(cmd2.ansi.style(arg, fg=self.songcolor))
+ self.poutput(cmd2.ansi.style(arg, fg=StdFg[self.songcolor.upper()]))
yo_parser = cmd2.Cmd2ArgumentParser()
yo_parser.add_argument('--ho', type=int, default=2, help="How often to chant 'ho'")
diff --git a/examples/plumbum_colors.py b/examples/plumbum_colors.py
deleted file mode 100755
index 6b0625f7..00000000
--- a/examples/plumbum_colors.py
+++ /dev/null
@@ -1,123 +0,0 @@
-#!/usr/bin/env python
-# coding=utf-8
-"""
-A sample application for cmd2. Demonstrating colorized output using the plumbum package.
-
-Experiment with the command line options on the `speak` command to see how
-different output colors ca
-
-The allow_style setting has three possible values:
-
-Never
- poutput(), pfeedback(), and ppaged() strip all ANSI style sequences
- which instruct the terminal to colorize output
-
-Terminal
- (the default value) poutput(), pfeedback(), and ppaged() do not strip any
- ANSI style sequences when the output is a terminal, but if the output is
- a pipe or a file the style sequences are stripped. If you want colorized
- output you must add ANSI style 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 style sequences,
- regardless of the output destination
-
-WARNING: This example requires the plumbum package, which isn't normally required by cmd2.
-"""
-
-from plumbum.colors import (
- bg,
- fg,
-)
-
-import cmd2
-from cmd2 import (
- ansi,
-)
-
-
-class FgColors(ansi.ColorBase):
- black = fg.Black
- red = fg.DarkRedA
- green = fg.MediumSpringGreen
- yellow = fg.LightYellow
- blue = fg.RoyalBlue1
- magenta = fg.Purple
- cyan = fg.SkyBlue1
- white = fg.White
- purple = fg.Purple
-
-
-class BgColors(ansi.ColorBase):
- black = bg.BLACK
- red = bg.DarkRedA
- green = bg.MediumSpringGreen
- yellow = bg.LightYellow
- blue = bg.RoyalBlue1
- magenta = bg.Purple
- cyan = bg.SkyBlue1
- white = bg.White
- purple = bg.Purple
-
-
-def get_fg(name: str) -> str:
- return str(FgColors[name])
-
-
-def get_bg(name: str) -> str:
- return str(BgColors[name])
-
-
-ansi.fg_lookup = get_fg
-ansi.bg_lookup = get_bg
-
-
-class CmdLineApp(cmd2.Cmd):
- """Example cmd2 application demonstrating colorized output."""
-
- def __init__(self):
- # Set include_ipy to True to enable the "ipy" command which runs an interactive IPython shell
- super().__init__(include_ipy=True)
-
- self.maxrepeats = 3
- # Make maxrepeats settable at runtime
- self.add_settable(cmd2.Settable('maxrepeats', int, 'max repetitions for speak command', self))
-
- # Should ANSI color output be allowed
- self.allow_style = ansi.STYLE_TERMINAL
-
- speak_parser = cmd2.Cmd2ArgumentParser()
- 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=FgColors.colors(), help='foreground color to apply to output')
- speak_parser.add_argument('-b', '--bg', choices=BgColors.colors(), help='background color to apply to output')
- speak_parser.add_argument('-l', '--bold', action='store_true', help='bold the output')
- speak_parser.add_argument('-u', '--underline', action='store_true', help='underline the output')
- speak_parser.add_argument('words', nargs='+', help='words to say')
-
- @cmd2.with_argparser(speak_parser)
- def do_speak(self, args):
- """Repeats what you tell me to."""
- words = []
- for word in args.words:
- if args.piglatin:
- word = '%s%say' % (word[1:], word[0])
- if args.shout:
- word = word.upper()
- words.append(word)
-
- repetitions = args.repeat or 1
- output_str = ansi.style(' '.join(words), fg=args.fg, bg=args.bg, bold=args.bold, underline=args.underline)
-
- for _ in range(min(repetitions, self.maxrepeats)):
- # .poutput handles newlines, and accommodates output redirection too
- self.poutput(output_str)
-
-
-if __name__ == '__main__':
- import sys
-
- c = CmdLineApp()
- sys.exit(c.cmdloop())
diff --git a/examples/table_creation.py b/examples/table_creation.py
index ff72311a..27045525 100755
--- a/examples/table_creation.py
+++ b/examples/table_creation.py
@@ -9,6 +9,7 @@ from typing import (
)
from cmd2 import (
+ StdFg,
ansi,
)
from cmd2.table_creator import (
@@ -32,9 +33,9 @@ class DollarFormatter:
# Text styles used in the data
-bold_yellow = functools.partial(ansi.style, fg=ansi.fg.bright_yellow, bold=True)
-blue = functools.partial(ansi.style, fg=ansi.fg.bright_blue)
-green = functools.partial(ansi.style, fg=ansi.fg.green)
+bold_yellow = functools.partial(ansi.style, fg=StdFg.LIGHT_YELLOW, bold=True)
+blue = functools.partial(ansi.style, fg=StdFg.LIGHT_BLUE)
+green = functools.partial(ansi.style, fg=StdFg.GREEN)
# Table Columns (width does not account for any borders or padding which may be added)
columns: List[Column] = list()
@@ -71,7 +72,7 @@ def ansi_print(text):
def main():
# Default to terminal mode so redirecting to a file won't include the ANSI style sequences
- ansi.allow_style = ansi.STYLE_TERMINAL
+ ansi.allow_style = ansi.AllowStyle.TERMINAL
st = SimpleTable(columns)
table = st.generate_table(data_list)