Python colorama.Style() Examples

The following are 15 code examples of colorama.Style(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module colorama , or try the search function .
Example #1
Source File: server.py    From byob with GNU General Public License v3.0 6 votes vote down vote up
def settings(self):
        """
        Show the server's currently configured settings

        """
        text_color = [color for color in filter(str.isupper, dir(colorama.Fore)) if color == self._text_color][0]
        text_style = [style for style in filter(str.isupper, dir(colorama.Style)) if style == self._text_style][0]
        prompt_color = [color for color in filter(str.isupper, dir(colorama.Fore)) if color == self._prompt_color][0]
        prompt_style = [style for style in filter(str.isupper, dir(colorama.Style)) if style == self._prompt_style][0]
        util.display('\n\t    OPTIONS', color='white', style='bright')
        util.display('text color/style: ', color='white', style='normal', end=' ')
        util.display('/'.join((self._text_color.title(), self._text_style.title())), color=self._text_color, style=self._text_style)
        util.display('prompt color/style: ', color='white', style='normal', end=' ')
        util.display('/'.join((self._prompt_color.title(), self._prompt_style.title())), color=self._prompt_color, style=self._prompt_style)
        util.display('debug: ', color='white', style='normal', end=' ')
        util.display('True\n' if globals()['debug'] else 'False\n', color='green' if globals()['debug'] else 'red', style='normal') 
Example #2
Source File: termcolors.py    From pipenv with MIT License 5 votes vote down vote up
def colorize(text, fg=None, bg=None, attrs=None):
    if os.getenv("ANSI_COLORS_DISABLED") is None:
        style = "NORMAL"
        if attrs is not None and not isinstance(attrs, list):
            _attrs = []
            if isinstance(attrs, six.string_types):
                _attrs.append(attrs)
            else:
                _attrs = list(attrs)
            attrs = _attrs
        if attrs and "bold" in attrs:
            style = "BRIGHT"
            attrs.remove("bold")
        if fg is not None:
            fg = fg.upper()
            text = to_native_string("%s%s%s%s%s") % (
                to_native_string(getattr(colorama.Fore, fg)),
                to_native_string(getattr(colorama.Style, style)),
                to_native_string(text),
                to_native_string(colorama.Fore.RESET),
                to_native_string(colorama.Style.NORMAL),
            )

        if bg is not None:
            bg = bg.upper()
            text = to_native_string("%s%s%s%s") % (
                to_native_string(getattr(colorama.Back, bg)),
                to_native_string(text),
                to_native_string(colorama.Back.RESET),
                to_native_string(colorama.Style.NORMAL),
            )

        if attrs is not None:
            fmt_str = to_native_string("%s[%%dm%%s%s[9m") % (chr(27), chr(27))
            for attr in attrs:
                text = fmt_str % (ATTRIBUTES[attr], text)

        text += RESET
    else:
        text = ANSI_REMOVAL_RE.sub("", text)
    return text 
Example #3
Source File: logger.py    From PyPPL with Apache License 2.0 5 votes vote down vote up
def format(self, record):
        if hasattr(record, 'formatted') and record.formatted:
            return record.formatted

        # save the formatted, for all handlers
        record.msg = str(record.msg)
        if '\n' in record.msg:
            record.tails = []
            msgs = record.msg.splitlines()
            record.msg = msgs[0]
            for msg in msgs[1:]:
                rec = copy(record)
                rec.msg = msg
                self.format(rec)
                record.tails.append(rec)

        proc = record.proc
        proc += (': '
                 if hasattr(record, 'proc') and record.proc
                 else '')
        jobs = ('' if record.jobidx is None
                else '[{ji}/{jt}] '.format(
                    ji=str(record.jobidx + 1).zfill(len(str(record.joblen))),
                    jt=record.joblen
                ))
        color = self.theme.get_color(record.mylevel)
        record.msg = (f" {color}{record.plugin:>7s}."
                      f"{record.mylevel:>7s}{colorama.Style.RESET_ALL}] "
                      f"{color}{proc}{jobs}{record.msg}"
                      f"{colorama.Style.RESET_ALL}")

        setattr(record, 'formatted', logging.Formatter.format(self, record))
        return record.formatted 
Example #4
Source File: options.py    From loopy with MIT License 5 votes vote down vote up
def _style(self):
        if self.allow_terminal_colors:
            import colorama
            return colorama.Style
        else:
            return _ColoramaStub() 
Example #5
Source File: util.py    From byob with GNU General Public License v3.0 5 votes vote down vote up
def display(output, color=None, style=None, end='\n', event=None, lock=None):
    """
    Display output in the console

    `Required`
    :param str output:    text to display

    `Optional`
    :param str color:     red, green, cyan, magenta, blue, white
    :param str style:     normal, bright, dim
    :param str end:       __future__.print_function keyword arg
    :param lock:          threading.Lock object
    :param event:         threading.Event object

    """
    # if isinstance(output, bytes):
    #     output = output.decode('utf-8')
    # else:
    #     output = str(output)
    # _color = ''
    # if color:
    #     _color = getattr(colorama.Fore, color.upper())
    # _style = ''
    # if style:
    #     _style = getattr(colorama.Style, style.upper())
    # exec("""print(_color + _style + output + colorama.Style.RESET_ALL, end="{}")""".format(end))
    print(output) 
Example #6
Source File: util.py    From byob with GNU General Public License v3.0 5 votes vote down vote up
def display(output, color=None, style=None, end='\n', event=None, lock=None):
    """
    Display output in the console

    `Required`
    :param str output:    text to display

    `Optional`
    :param str color:     red, green, cyan, magenta, blue, white
    :param str style:     normal, bright, dim
    :param str end:       __future__.print_function keyword arg
    :param lock:          threading.Lock object
    :param event:         threading.Event object

    """
    # if isinstance(output, bytes):
    #     output = output.decode('utf-8')
    # else:
    #     output = str(output)
    # _color = ''
    # if color:
    #     _color = getattr(colorama.Fore, color.upper())
    # _style = ''
    # if style:
    #     _style = getattr(colorama.Style, style.upper())
    # exec("""print(_color + _style + output + colorama.Style.RESET_ALL, end="{}")""".format(end))
    print(output) 
Example #7
Source File: server.py    From byob with GNU General Public License v3.0 5 votes vote down vote up
def _get_prompt(self, data):
        with self._lock:
            return raw_input(getattr(colorama.Fore, self._prompt_color) + getattr(colorama.Style, self._prompt_style) + data.rstrip()) 
Example #8
Source File: util.py    From byob with GNU General Public License v3.0 5 votes vote down vote up
def display(output, color=None, style=None, end='\\n', event=None, lock=None):
    """
    Display output in the console

    `Required`
    :param str output:    text to display

    `Optional`
    :param str color:     red, green, cyan, magenta, blue, white
    :param str style:     normal, bright, dim
    :param str end:       __future__.print_function keyword arg
    :param lock:          threading.Lock object
    :param event:         threading.Event object

    """
    if isinstance(output, bytes):
        output = output.decode('utf-8')
    else:
        output = str(output)
    _color = ''
    if color:
        _color = getattr(colorama.Fore, color.upper())
    _style = ''
    if style:
        _style = getattr(colorama.Style, style.upper())
    exec("""print(_color + _style + output + colorama.Style.RESET_ALL, end="{}")""".format(end)) 
Example #9
Source File: color.py    From incubator-ariatosca with Apache License 2.0 5 votes vote down vote up
def highlight(self, pattern, schema):
        if pattern is None:
            return
        for match in set(re.findall(re.compile(pattern), self._str)):
            self.replace(match, schema + match + Colors.Style.RESET_ALL + self._color_spec) 
Example #10
Source File: termcolors.py    From vistir with ISC License 5 votes vote down vote up
def colorize(text, fg=None, bg=None, attrs=None):
    if os.getenv("ANSI_COLORS_DISABLED") is None:
        style = "NORMAL"
        if attrs is not None and not isinstance(attrs, list):
            _attrs = []
            if isinstance(attrs, six.string_types):
                _attrs.append(attrs)
            else:
                _attrs = list(attrs)
            attrs = _attrs
        if attrs and "bold" in attrs:
            style = "BRIGHT"
            attrs.remove("bold")
        if fg is not None:
            fg = fg.upper()
            text = to_native_string("%s%s%s%s%s") % (
                to_native_string(getattr(colorama.Fore, fg)),
                to_native_string(getattr(colorama.Style, style)),
                to_native_string(text),
                to_native_string(colorama.Fore.RESET),
                to_native_string(colorama.Style.NORMAL),
            )

        if bg is not None:
            bg = bg.upper()
            text = to_native_string("%s%s%s%s") % (
                to_native_string(getattr(colorama.Back, bg)),
                to_native_string(text),
                to_native_string(colorama.Back.RESET),
                to_native_string(colorama.Style.NORMAL),
            )

        if attrs is not None:
            fmt_str = to_native_string("%s[%%dm%%s%s[9m") % (chr(27), chr(27))
            for attr in attrs:
                text = fmt_str % (ATTRIBUTES[attr], text)

        text += RESET
    else:
        text = ANSI_REMOVAL_RE.sub("", text)
    return text 
Example #11
Source File: io.py    From evillimiter with MIT License 5 votes vote down vote up
def ok(text, end='\n'):
        """
        Print a success status message
        """
        IO.print('{}OK{}   {}'.format(IO.Style.BRIGHT + IO.Fore.LIGHTGREEN_EX, IO.Style.RESET_ALL, text), end=end) 
Example #12
Source File: io.py    From evillimiter with MIT License 5 votes vote down vote up
def error(text):
        """
        Print an error status message
        """
        IO.print('{}ERR{}  {}'.format(IO.Style.BRIGHT + IO.Fore.LIGHTRED_EX, IO.Style.RESET_ALL, text)) 
Example #13
Source File: crayons.py    From crayons with MIT License 5 votes vote down vote up
def color_str(self):
        style = 'BRIGHT' if self.bold else 'NORMAL'
        c = '%s%s%s%s%s' % (getattr(colorama.Fore, self.color),
                            getattr(colorama.Style, style),
                            self.s,
                            colorama.Fore.RESET,
                            colorama.Style.NORMAL)

        if self.always_color:
            return c
        elif sys.stdout.isatty() and not DISABLE_COLOR:
            return c
        else:
            return self.s 
Example #14
Source File: server.py    From byob with GNU General Public License v3.0 4 votes vote down vote up
def set(self, args=None):
        """
        Set display settings for the command & control console

        Usage: `set [setting] [option]=[value]`

            :setting text:      text displayed in console
            :setting prompt:    prompt displayed in shells

            :option color:      color attribute of a setting
            :option style:      style attribute of a setting

            :values color:      red, green, cyan, yellow, magenta
            :values style:      normal, bright, dim

        Example 1:         `set text color=green style=normal`
        Example 2:         `set prompt color=white style=bright`

        """
        if args:
            arguments = self._get_arguments(args)
            args, kwargs = arguments.args, arguments.kwargs
            if arguments.args:
                target = args[0]
                args = args[1:]
                if target in ('debug','debugging'):
                    if args:
                        setting = args[0]
                        if setting.lower() in ('0','off','false','disable'):
                            globals()['debug'] = False
                        elif setting.lower() in ('1','on','true','enable'):
                            globals()['debug'] = True
                        util.display("\n[+]" if globals()['debug'] else "\n[-]", color='green' if globals()['debug'] else 'red', style='normal', end=' ')
                        util.display("Debug: {}\n".format("ON" if globals()['debug'] else "OFF"), color='white', style='bright')
                        return
                for setting, option in arguments.kwargs.items():
                    option = option.upper()
                    if target == 'prompt':
                        if setting == 'color':
                            if hasattr(colorama.Fore, option):
                                self._prompt_color = option
                        elif setting == 'style':
                            if hasattr(colorama.Style, option):
                                self._prompt_style = option
                        util.display("\nprompt color/style changed to ", color='white', style='bright', end=' ')
                        util.display(option + '\n', color=self._prompt_color, style=self._prompt_style)
                        return
                    elif target == 'text':
                        if setting == 'color':
                            if hasattr(colorama.Fore, option):
                                self._text_color = option
                        elif setting == 'style':
                            if hasattr(colorama.Style, option):
                                self._text_style = option
                        util.display("\ntext color/style changed to ", color='white', style='bright', end=' ')
                        util.display(option + '\n', color=self._text_color, style=self._text_style)
                        return
        util.display("\nusage: set [setting] [option]=[value]\n\n    colors:   white/black/red/yellow/green/cyan/magenta\n    styles:   dim/normal/bright\n", color=self._text_color, style=self._text_style) 
Example #15
Source File: color.py    From incubator-ariatosca with Apache License 2.0 4 votes vote down vote up
def __repr__(self):
        if self._color_spec:
            return '{schema}{str}{reset}'.format(
                schema=self._color_spec, str=safe_str(self._str), reset=Colors.Style.RESET_ALL)
        return self._str