示例#1
0
    def _draw_line(self, line, isheader=False):
        """Draw a line

        Loop over a single cell length, over all the cells
        """

        line = self._splitit(line, isheader)
        space = " "
        out = ""
        for i in range(len(line[0])):
            if self._has_border():
                out += "%s " % self._char_vert
            length = 0
            for cell, width, align in zip(line, self._width, self._align):
                length += 1
                cell_line = cell[i]
                fill = width - len(cell_line)
                if isheader:
                    align = "c"
                    cell_line = termcolor.colored(cell_line, attrs=["bold"])
                if align == "r":
                    out += "%s " % (fill * space + cell_line)
                elif align == "c":
                    out += "%s " % (int(fill / 2) * space + cell_line
                                    + int(fill / 2 + fill % 2) * space)
                else:
                    out += "%s " % (cell_line + fill * space)
                if length < len(line):
                    out += "%s " % [space, self._char_vert][self._has_vlines()]
            out += "%s\n" % ['', self._char_vert][self._has_border()]
        return out
示例#2
0
def color_text(text, *args, **kwargs):
    """Use :any:`termcolor.colored` to colorize text.
    
    Args:
        text (str): Text to colorize.
        *args: Positional arguments to pass to :any:`termcolor.colored`.
        **kwargs: Keyword arguments to pass to :any:`termcolor.colored`.
        
    Returns:
        str: The colorized text.
    """
    return termcolor.colored(text, *args, **kwargs)
示例#3
0
def main(COLOR="red", CommandLine=True, filler_file="", template_file=""):
	if CommandLine:
		usage = "usage: %prog [options] template_file filler_file"
		parser = OptionParser(usage=usage)
		parser.add_option("-n","--new", dest="new", action="store_true",
			default=False, help="Create a new filler file")
		(options, args) = parser.parse_args()
		if len(args) != 2:
			parser.error("bad arguments")
		template_file = args[0]
		filler_file = args[1]
	
	if CommandLine and options.new:
		with open(template_file) as template_f:
			with open(filler_file, 'w') as filler_f:
				script_text = template_f.read()
				segments = script_text.split("\n\n")
				for segment in segments:
					print segment
					slots = re.findall("SLOT\d", segment)
					for slot in slots:
						lol = raw_input(slot + " > ") # actual input :)
						filler_f.write(slot + " " + lol + "\n")
				print "COMPLETE"
	else:
		with open(template_file) as template_f:
			with open(filler_file) as filler_f:
				script_text = template_f.read()
				for line in filler_f:
					line = line.strip()
					if line == "": continue
					split_line = line.split(" ")
					script_text = script_text.replace( split_line[0],
									 colored(" ".join(split_line[1:]).strip().upper(), COLOR ) )
				segments = script_text.split("\n\n")
				for segment in segments:
					print segment
					lol = raw_input("> ") # barely an illusion of choice
				print colored("CONGRATULATION", COLOR, attrs=['blink','bold','underline','dark'])
示例#4
0
    def set_chars(self, array, char_color='white'):
        """Set the characters used to draw lines between rows and columns

        - the array should contain 4 fields:

            [horizontal, vertical, corner, header]

        - default is set to:

            ['-', '|', '+', '=']
        """

        if len(array) != 4:
            raise ArraySizeError("array should contain 4 characters")
        array = [termcolor.colored(x[:1], char_color) for x in [str(s) for s in array]]
        (self._char_horiz, self._char_vert,
            self._char_corner, self._char_header) = array
示例#5
0
 def dashboard_format(self, models):
     """Format modeled records in dashboard format.
     
     Args:
         models: Modeled records to format.
     
     Returns:
         str: Record data in dashboard format.
     """
     self.logger.debug("Dashboard format")
     title = util.hline("%s Configurations (%s)" %
                        (models[0].name.capitalize(), 
                         models[0].storage),
                        'cyan')
     header_row = [col['header'] for col in self.dashboard_columns]
     rows = [header_row]
     for model in models:
         populated = model.populate()
         row = []
         for col in self.dashboard_columns:
             if 'value' in col:
                 try:
                     cell = populated[col['value']]
                 except KeyError:
                     cell = 'N/A'
             elif 'yesno' in col:
                 cell = 'Yes' if populated.get(col['yesno'], False) else 'No'
             elif 'function' in col:
                 cell = col['function'](populated)
             else:
                 raise InternalError("Invalid column definition: %s" % col)
             color_attrs = col.get('color_attrs', None)
             if color_attrs:
                 cell = termcolor.colored(cell, **color_attrs)
             row.append(cell)
         rows.append(row)
     table = Texttable(logger.LINE_WIDTH)
     table.set_cols_align([col.get('align', 'c') for col in self.dashboard_columns])
     table.add_rows(rows)
     return [title, table.draw(), '']
示例#6
0
    def _colored(self, text, *color_args):
        """Insert ANSII color formatting via `termcolor`_.
        
        Text colors:
            * grey
            * red
            * green
            * yellow
            * blue
            * magenta
            * cyan
            * white
        
        Text highlights:
            * on_grey
            * on_red
            * on_green
            * on_yellow
            * on_blue
            * on_magenta
            * on_cyan
            * on_white

        Attributes:
            * bold
            * dark
            * underline
            * blink
            * reverse
            * concealed
        
        .. _termcolor: http://pypi.python.org/pypi/termcolor
        """
        if self.allow_colors and color_args:
            return termcolor.colored(text, *color_args)
        else:
            return text
示例#7
0
    def _colored(self, text, *color_args):
        """Insert ANSII color formatting via `termcolor`_.
        
        Text colors:
            * grey
            * red
            * green
            * yellow
            * blue
            * magenta
            * cyan
            * white
        
        Text highlights:
            * on_grey
            * on_red
            * on_green
            * on_yellow
            * on_blue
            * on_magenta
            * on_cyan
            * on_white

        Attributes:
            * bold
            * dark
            * underline
            * blink
            * reverse
            * concealed
        
        .. _termcolor: http://pypi.python.org/pypi/termcolor
        """
        if self.allow_colors and color_args:
            return termcolor.colored(text, *color_args)
        else:
            return text
示例#8
0
    LOG_LEVEL = level.upper()
    _STDOUT_HANDLER.setLevel(LOG_LEVEL)
    
LOG_LEVEL = 'INFO'
"""str: The global logging level for stdout loggers and software packages.

Don't change directly. May be changed via :any:`set_log_level`.  
"""

LOG_FILE = os.path.join(USER_PREFIX, 'debug_log')
"""str: Absolute path to a log file to receive all debugging output."""

LINE_MARKER = os.environ.get('TAU_LINE_MARKER', '[TAU] ')
"""str: Marker for each line of output."""

COLORED_LINE_MARKER = termcolor.colored(LINE_MARKER, 'red')

TERM_SIZE = get_terminal_size()
"""tuple: (width, height) tuple of detected terminal dimensions in characters."""

LINE_WIDTH = TERM_SIZE[0] - len(LINE_MARKER)
"""Width of a line on the terminal.

Uses system specific methods to determine console line width.  If the line
width cannot be determined, the default is 80.
"""

_ROOT_LOGGER = logging.getLogger()
if not _ROOT_LOGGER.handlers:
    _ROOT_LOGGER.setLevel(logging.DEBUG)
    _LOG_FILE_PREFIX = os.path.dirname(LOG_FILE)
示例#9
0
__author__ = 'am004929'

import time
from random import choice

from termcolor.termcolor import colored

COLORS = ('blue', 'red', 'green', 'magenta', 'white', 'yellow')

while(1):
    print colored('Bark!', choice(COLORS))
    time.sleep(1)
示例#10
0
def color_text(text, *args, **kwargs):
    return termcolor.colored(text, *args, **kwargs)
示例#11
0
def hline(title, *color_args):
    text = "{:=<{}}\n".format('== %s ==' % title, logger.LINE_WIDTH)
    if color_args:
        return termcolor.colored(text, *color_args)
    else:
        return text
示例#12
0
    LOG_LEVEL = level.upper()
    _STDOUT_HANDLER.setLevel(LOG_LEVEL)
    
LOG_LEVEL = 'INFO'
"""str: The global logging level for stdout loggers and software packages.

Don't change directly. May be changed via :any:`set_log_level`.  
"""

LOG_FILE = os.path.join(USER_PREFIX, 'debug_log')
"""str: Absolute path to a log file to receive all debugging output."""

LINE_MARKER = os.environ.get('TAU_LINE_MARKER', '[TAU] ')
"""str: Marker for each line of output."""

COLORED_LINE_MARKER = termcolor.colored(LINE_MARKER, 'red')

TERM_SIZE = get_terminal_size()
"""tuple: (width, height) tuple of detected terminal dimensions in characters."""

LINE_WIDTH = TERM_SIZE[0] - len(LINE_MARKER)
"""Width of a line on the terminal.

Uses system specific methods to determine console line width.  If the line
width cannot be determined, the default is 80.
"""

_ROOT_LOGGER = logging.getLogger()
if not len(_ROOT_LOGGER.handlers):
    _ROOT_LOGGER.setLevel(logging.DEBUG)
    _LOG_FILE_PREFIX = os.path.dirname(LOG_FILE)
示例#13
0
 def draw(self):
     print(colored(self.symbol, self.colour), end="")
#author: fptrainnie
# -*- coding: utf-8 -*-
import subprocess
import os
import sys
from termcolor.termcolor import colored

if __name__ == '__main__':
    env = os.environ
    env['PYTHONIOENCODING'] = 'utf-8' 
    pan = subprocess.Popen(['python','info_dump.py','--port=/dev/ttyUSB1','--baud=57600','10'], stdout=subprocess.PIPE, env=env)
    out, err =  pan.communicate() 
    if out.split()[4] == 'done':
        print 'Neck: Pan\t' + out.split()[1] + colored(out.split()[2],'yellow') + out.split()[3] + colored(out.split()[4],'green')
        print '\t' + out.split()[25] + out.split()[26] + out.split()[27] + colored(out.split()[28],'cyan')
    else:
        print 'Neck: Pan\t' + out.split()[1] + colored(out.split()[2],'red') + out.split()[3] + colored(out.split()[4],'red')
    print

    tilt = subprocess.Popen(['python','info_dump.py','--port=/dev/ttyUSB1','--baud=57600','11'], stdout=subprocess.PIPE, env=env)
    out, err = tilt.communicate()
    if out.split()[4] == 'done':
        print 'Neck: Tilt\t' + out.split()[1] + colored(out.split()[2],'yellow') + out.split()[3] + colored(out.split()[4],'green')
        print '\t' + out.split()[25] + out.split()[26] + out.split()[27] + colored(out.split()[28],'cyan')
    else:
        print 'Neck: Tilt\t' + out.split()[1] + colored(out.split()[2],'red') + out.split()[3] + colored(out.split()[4],'red')
    print 

    shd_in_r = subprocess.Popen(['python','info_dump.py','--port=/dev/ttyUSB1','--baud=57600','20'], stdout=subprocess.PIPE, env=env)
    out, err = shd_in_r.communicate()
    if out.split()[4] == 'done':
示例#15
0
def print_colored(message, color):
    print(colored(message, color))