Skip to content

Instantly share code, notes, and snippets.

@zhasm
Created July 19, 2017 08:08
Show Gist options
  • Save zhasm/ee4789b0ebf8dd0af55e8c75fe5be359 to your computer and use it in GitHub Desktop.
Save zhasm/ee4789b0ebf8dd0af55e8c75fe5be359 to your computer and use it in GitHub Desktop.
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')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment