zhasm
7/19/2017 - 8:08 AM

declare python dynamic functions

declare python dynamic functions

# -*- encoding: utf-8 -*-

"""
在globals()这个{}里添加一组 key: value
key: 函数名,字符串
value: 函数的定义。
"""


import sys

colors = [
    'red',
    'blue',
    'cyan',
    'green',
    'bold',
    'reverse',
]

RED   = "\033[1;31m"  
BLUE  = "\033[1;34m"
CYAN  = "\033[1;36m"
GREEN = "\033[0;32m"
RESET = "\033[0;0m"
BOLD    = "\033[;1m"
REVERSE = "\033[;7m"


def register_color_funcs(cl):

    def _color(cl, *args):
        cl = globals()[cl.upper()]
        sp = ' '
        sys.stdout.write(cl)
        print sp.join((str(i) for i in args))
        sys.stdout.write(RESET)

    globals()[cl] = lambda *args: _color(cl, *args)

def init_color_funcs():
    for c in colors:
        register_color_funcs(c)

init_color_funcs()

""" now functions red, green, bold, cyan  are available"""

red('red', 'hello', 'red world')
green('green', 'green ', 'world')
bold('bold', 'green ', 'world')
cyan('cyan', 'green ', 'world')