Skip to content

Instantly share code, notes, and snippets.

Created January 7, 2013 04:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/4472264 to your computer and use it in GitHub Desktop.
Save anonymous/4472264 to your computer and use it in GitHub Desktop.
Playing with termcolor.py
import time
import sys
import random
import termcolor
colors = "grey", "red", "green", "yellow", "blue", "magenta", "cyan"
attributes = "bold", "underline", "blink", "reverse"
def random_color():
return random.choice(colors)
def random_on_color():
return "on_" + random_color()
def random_attribute():
return [random.choice(attributes)]
def random_char():
return chr(random.randint(33,126))
# These are the different arguments that can be used for printing colored characters
# Each one is given an associated function for selecting its value at random.
arg_funcs = {"color": random_color,
"on_color": random_on_color,
"attrs": random_attribute,
}
# Get a list of just the arg names (saves us from typing the names again!)
arg_names = arg_funcs.keys()
while(True):
# Select between 1 and 3 args to use at random (not counting the "char" argument
# which is always requred).
args_to_use = random.sample(arg_names, random.randrange(1, 3))
# Create a dict of argument names and random values to use when printing
# The colored character. When calling a method or function, dictionaries can be
# used as a collection of keyword arguments by using the double star (**dict) notation.
random_values = [arg_funcs[arg_name]() for arg_name in args_to_use]
arg_dict = dict(zip(args_to_use, random_values))
# uncomment this to test the argument selection logic:
#print arg_dict
# Call termcolor like this:
termcolor.colored(random_char(), **arg_dict)
sys.stdout.flush()
time.sleep(0.3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment