本文整理汇总了Python中xtermcolor.colorize函数的典型用法代码示例。如果您正苦于以下问题:Python colorize函数的具体用法?Python colorize怎么用?Python colorize使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了colorize函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate_license_file
def generate_license_file(license, owner):
""" Generates a license file and populate it accordingly.
Asks user for extra context variables if any in the license.
"""
template_file_path = join(dirname(__file__), "../data/template/%s.tmpl" %
(license))
template_file = abspath(template_file_path)
with open(template_file) as f:
content = f.read()
parsed_context = parse_template(content)
default_context_keys = ['owner', 'year']
context = {'year': datetime.now().year, 'owner': owner}
extra_context = {}
if (len(parsed_context) > len(default_context_keys)):
for key in parsed_context:
if key not in default_context_keys:
print colorize(
"\n%s license also asks for %s. What do you want to fill there?"
% (license, key),
ansi=4)
extra_context[key] = raw_input().strip()
arguments = context.copy()
arguments.update(extra_context)
template = Template(content)
content = template.render(arguments)
with open('LICENSE', 'w') as f:
f.write(content)
示例2: load_relation
def load_relation(filename, defname=None):
if not os.path.isfile(filename):
print (colorize(
"%s is not a file" % filename, ERROR_COLOR), file=sys.stderr)
return None
f = filename.split('/')
if defname == None:
defname = f[len(f) - 1].lower()
if defname.endswith(".csv"): # removes the extension
defname = defname[:-4]
if not rtypes.is_valid_relation_name(defname):
print (colorize(
"%s is not a valid relation name" % defname, ERROR_COLOR), file=sys.stderr)
return
try:
relations[defname] = relation.relation(filename)
completer.add_completion(defname)
printtty(colorize("Loaded relation %s" % defname, 0x00ff00))
return defname
except Exception as e:
print (colorize(e, ERROR_COLOR), file=sys.stderr)
return None
示例3: cli
def cli():
parser = argparse.ArgumentParser(description=description, epilog='Created by Scott Frazer (https://github.com/scottfrazer)', formatter_class=RawTextHelpFormatter)
parser.add_argument('--version', action='version', version=str(pkg_resources.get_distribution('mdtoc')))
parser.add_argument('markdown_file')
parser.add_argument('--check-links', action='store_true', help="Find all hyperlinks and ensure that \nthey point to something valid")
cli = parser.parse_args()
cli.markdown_file = os.path.expanduser(cli.markdown_file)
if not os.path.isfile(cli.markdown_file):
sys.exit('File not found: {}'.format(cli.markdown_file))
modify_and_write(cli.markdown_file)
if cli.check_links:
with open(cli.markdown_file) as fp:
contents = fp.read()
valid_http_fragments = ['#'+as_link(h) for (l, h) in headers(contents)]
for (text, link, line, col) in get_links(contents):
valid = 'unrecognized link type'
if link.startswith('#'):
if link not in valid_http_fragments:
valid = colorize('INVALID', ansi=1)
else:
valid = colorize('VALID', ansi=2)
elif link.startswith('http://') or link.startswith('https://'):
r = requests.get(link)
valid = 'Response: {}'.format(r.status_code)
print('Checking {line}:{col} [{text}]({link}) --> {valid} '.format(
text=colorize(text, ansi=3),
link=colorize(link, ansi=4),
line=line,
col=col,
valid=valid
))
示例4: main
def main(files=[]):
printtty(colorize('> ', PROMPT_COLOR) + "; Type HELP to get the HELP")
printtty(colorize('> ', PROMPT_COLOR) +
"; Completion is activated using the tab (if supported by the terminal)")
for i in files:
load_relation(i)
readline.set_completer(completer.complete)
readline.parse_and_bind('tab: complete')
readline.parse_and_bind('set editing-mode emacs')
readline.set_completer_delims(" ")
while True:
try:
line = input(colorize('> ' if TTY else '', PROMPT_COLOR))
if isinstance(line, str) and len(line) > 0:
exec_line(line)
except KeyboardInterrupt:
if TTY:
print ('^C\n')
continue
else:
break
except EOFError:
printtty()
sys.exit(0)
示例5: exec_query
def exec_query(command):
'''This function executes a query and prints the result on the screen
if the command terminates with ";" the result will not be printed
'''
# If it terminates with ; doesn't print the result
if command.endswith(';'):
command = command[:-1]
printrel = False
else:
printrel = True
# Performs replacements for weird operators
command = replacements(command)
# Finds the name in where to save the query
parts = command.split('=', 1)
relname,query = maintenance.UserInterface.split_query(command)
# Execute query
try:
pyquery = parser.parse(query)
result = pyquery(relations)
printtty(colorize("-> query: %s" % pyquery, 0x00ff00))
if printrel:
print ()
print (result)
relations[relname] = result
completer.add_completion(relname)
except Exception as e:
print (colorize(str(e), ERROR_COLOR))
示例6: load_relation
def load_relation(filename: str, defname:Optional[str]=None) -> Optional[str]:
'''
Loads a relation into the set. Defname is the given name
to the relation.
Returns the name to the relation, or None if it was
not loaded.
'''
if not os.path.isfile(filename):
print(colorize(
"%s is not a file" % filename, ERROR_COLOR), file=sys.stderr)
return None
if defname is None:
f = filename.split('/')
defname = f[-1].lower()
if defname.endswith(".csv"): # removes the extension
defname = defname[:-4]
if not rtypes.is_valid_relation_name(defname):
print(colorize(
"%s is not a valid relation name" % defname, ERROR_COLOR), file=sys.stderr)
return None
try:
relations[defname] = relation.relation(filename)
completer.add_completion(defname)
printtty(colorize("Loaded relation %s" % defname, COLOR_GREEN))
return defname
except Exception as e:
print(colorize(str(e), ERROR_COLOR), file=sys.stderr)
return None
示例7: run_fail_test
def run_fail_test(testname):
'''Runs a test, which executes a query that is supposed to fail'''
print ("Running fail test: " + colorize(testname, COLOR_MAGENTA))
query = readfile('%s%s.fail' % (tests_path, testname)).strip()
test_succeed = True
try:
expr = parser.parse(query)
expr(rels)
test_succeed = False
except:
pass
try:
o_query = optimizer.optimize_all(query, rels)
o_expr = parser.parse(o_query)
o_expr(rels)
test_succeed = False
except:
pass
try:
c_expr = parser.tree(query).toCode()
eval(c_expr, rels)
test_succeed = False
except:
pass
if test_succeed:
print (colorize('Test passed', COLOR_GREEN))
else:
print (colorize('Test failed (by not raising any exception)', COLOR_RED))
return test_succeed
示例8: check_for_sdk_updates
def check_for_sdk_updates(auto_update_prompt=False):
try:
theirs = get_latest_version()
yours = config.VERSION
except LatestVersionCheckError:
return
if theirs <= yours:
return
url = 'https://github.com/grow/grow/releases/tag/{}'.format(theirs)
logging.info('')
logging.info(' Please update to the newest version of the Grow SDK.')
logging.info(' See release notes: {}'.format(url))
logging.info(' Your version: {}, latest version: {}'.format(
colorize(yours, ansi=226), colorize(theirs, ansi=82)))
if utils.is_packaged_app() and auto_update_prompt:
# If the installation was successful, restart the process.
try:
if (raw_input('Auto update now? [y/N]: ').lower() == 'y'
and subprocess.call(INSTALLER_COMMAND, shell=True) == 0):
logging.info('Restarting...')
os.execl(sys.argv[0], *sys.argv)
except Exception as e:
text = (
'In-place update failed. Update manually or use:\n'
' curl https://install.growsdk.org | bash')
logging.error(text)
sys.exit(-1)
else:
logging.info(' Update using: ' + colorize('pip install --upgrade grow', ansi=200))
print ''
示例9: colored_change
def colored_change(old, new, unit='', inverse=False):
condition = old > new
if inverse: condition = not condition
if condition:
return colorize(str(old) + unit, ansi=9) + ' -> ' + colorize(str(new) + unit, ansi=2)
else:
return colorize(str(old) + unit, ansi=2) + ' -> ' + colorize(str(new) + unit, ansi=9)
示例10: compute_graph_matrix
def compute_graph_matrix(self):
"""
Compute and return contribution graph matrix
"""
logger.debug("Printing graph")
sorted_normalized_daily_contribution = sorted(self.daily_contribution_map)
matrix = []
first_day = sorted_normalized_daily_contribution[0]
if first_day.strftime("%A") != "Sunday":
c = self._Column(self.width)
d = first_day - datetime.timedelta(days=1)
while d.strftime("%A") != "Saturday":
d = d - datetime.timedelta(days=1)
c.append([None, self.width])
matrix.append(c)
else:
new_column = self._Column(self.width)
matrix.append(new_column)
for current_day in sorted_normalized_daily_contribution:
last_week_col = matrix[-1]
day_contribution_color_index = int(self.daily_contribution_map[current_day])
color = self.colors[day_contribution_color_index]
try:
last_week_col.append([current_day, colorize(self.width,
ansi=0,
ansi_bg=color)])
except ValueError: # column (e.g. week) has ended
new_column = self._Column(self.width)
matrix.append(new_column)
last_week_col = matrix[-1]
last_week_col.append([current_day, colorize(self.width,
ansi=0,
ansi_bg=color)])
next_day = current_day + datetime.timedelta(days=1)
if next_day.month != current_day.month:
# if the column we're at isn't 7 days yet, fill it with empty blocks
last_week_col.fill()
# make new empty col to separate months
matrix.append(self._Column(self.width, full_empty_col=True))
matrix.append(self._Column(self.width))
last_week_col = matrix[-1] # update to the latest column
# if next_day (which is first day of new month) starts in middle of the
# week, prepend empty blocks in the column before inserting 'next day'
next_day_num = DAYS.index(next_day.strftime("%A"))
last_week_col.fill_by(next_day_num)
# make sure that the most current week (last col of matrix) col is of size 7,
# so fill it if it's not
matrix[-1].fill()
return matrix
示例11: start
def start(pod, host=None, port=None, open_browser=False, debug=False,
preprocess=True):
observer, podspec_observer = file_watchers.create_dev_server_observers(pod)
if preprocess:
# Run preprocessors for the first time in a thread.
thread = threading.Thread(target=pod.preprocess)
thread.start()
try:
# Create the development server.
app = main_lib.CreateWSGIApplication(pod)
port = 8080 if port is None else int(port)
host = 'localhost' if host is None else host
num_tries = 0
while num_tries < 10:
try:
httpd = simple_server.make_server(host, port, app,
handler_class=DevServerWSGIRequestHandler)
num_tries = 99
except socket.error as e:
if e.errno == 48:
num_tries += 1
port += 1
else:
raise e
except Exception as e:
logging.error('Failed to start server: {}'.format(e))
observer.stop()
observer.join()
sys.exit()
try:
root_path = pod.get_root_path()
url = 'http://{}:{}{}'.format(host, port, root_path)
print 'Pod: '.rjust(20) + pod.root
print 'Address: '.rjust(20) + url
print colorize('Server ready. '.rjust(20), ansi=47) + 'Press ctrl-c to quit.'
def start_browser(server_ready_event):
server_ready_event.wait()
if open_browser:
webbrowser.open(url)
server_ready_event = threading.Event()
browser_thread = threading.Thread(target=start_browser,
args=(server_ready_event,))
browser_thread.start()
server_ready_event.set()
httpd.serve_forever()
browser_thread.join()
except KeyboardInterrupt:
logging.info('Goodbye. Shutting down.')
httpd.server_close()
observer.stop()
observer.join()
# Clean up once server exits.
sys.exit()
示例12: generate_list
def generate_list():
""" Prints listing of all the available licenses.
"""
print colorize("Lisense currently supports %d licenses.\n" %
(len(catalogue)),
ansi=4)
for label, license in catalogue.iteritems():
print colorize("- %s" % (license), ansi=253)
示例13: print_server_ready_message
def print_server_ready_message(pod, host, port):
home_doc = pod.get_home_doc()
if home_doc:
root_path = home_doc.url.path
else:
root_path = pod.get_root_path()
url = 'http://{}:{}{}'.format(host, port, root_path)
print 'Pod: '.rjust(20) + pod.root
print 'Address: '.rjust(20) + url
print colorize('Server ready. '.rjust(20), ansi=47) + 'Press ctrl-c to quit.'
return url
示例14: log_request
def log_request(self, code=0, size='-'):
if not self._logging_enabled:
return
line = self.requestline[:-9]
method, line = line.split(' ', 1)
color = 19
if int(code) >= 500:
color = 161
code = colorize(code, ansi=color)
size = colorize(DevServerWSGIRequestHandler.sizeof(size), ansi=19)
self.log_message('{} {} {}'.format(code, line, size))
示例15: machine_translate
def machine_translate(pod_path, locale):
"""Translates the pod message catalog using machine translation."""
root = os.path.abspath(os.path.join(os.getcwd(), pod_path))
pod = pods.Pod(root, storage=storage.FileStorage)
pod.catalogs.extract()
for locale in locale:
catalog = pod.catalogs.get(locale)
catalog.update()
catalog.machine_translate()
print colorize('WARNING! Use machine translations with caution.', ansi=197)
print colorize('Machine translations are not intended for use in production.', ansi=197)