本文整理汇总了Python中xonsh.tools.print_color函数的典型用法代码示例。如果您正苦于以下问题:Python print_color函数的具体用法?Python print_color怎么用?Python print_color使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了print_color函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: pinfo
def pinfo(self, obj, oname='', info=None, detail_level=0):
"""Show detailed information about an object.
Parameters
----------
obj : object
oname : str, optional
name of the variable pointing to the object.
info : dict, optional
a structure with some information fields which may have been
precomputed already.
detail_level : int, optional
if set to 1, more information is given.
"""
info = self.info(obj,
oname=oname,
info=info,
detail_level=detail_level)
displayfields = []
def add_fields(fields):
for title, key in fields:
field = info[key]
if field is not None:
displayfields.append((title, field.rstrip()))
add_fields(self.pinfo_fields1)
add_fields(self.pinfo_fields2)
# Namespace
if (info['namespace'] is not None and
info['namespace'] != 'Interactive'):
displayfields.append(("Namespace", info['namespace'].rstrip()))
add_fields(self.pinfo_fields3)
if info['isclass'] and info['init_definition']:
displayfields.append(("Init definition",
info['init_definition'].rstrip()))
# Source or docstring, depending on detail level and whether
# source found.
if detail_level > 0 and info['source'] is not None:
displayfields.append(("Source", cast_unicode(info['source'])))
elif info['docstring'] is not None:
displayfields.append(("Docstring", info["docstring"]))
# Constructor info for classes
if info['isclass']:
if info['init_docstring'] is not None:
displayfields.append(("Init docstring",
info['init_docstring']))
# Info for objects:
else:
add_fields(self.pinfo_fields_obj)
# Finally send to printer/pager:
if displayfields:
print_color(self._format_fields(displayfields))
示例2: _colors
def _colors(ns):
cols, _ = shutil.get_terminal_size()
cmap = tools.color_style()
akey = next(iter(cmap))
if isinstance(akey, str):
s = _str_colors(cmap, cols)
else:
s = _tok_colors(cmap, cols)
tools.print_color(s)
示例3: help
def help(self, key):
"""Get information about a specific enviroment variable."""
vardocs = self.get_docs(key)
width = min(79, os.get_terminal_size()[0])
docstr = "\n".join(textwrap.wrap(vardocs.docstr, width=width))
template = HELP_TEMPLATE.format(
envvar=key, docstr=docstr, default=vardocs.default, configurable=vardocs.configurable
)
print_color(template)
示例4: print_welcome_screen
def print_welcome_screen():
subst = dict(tagline=random.choice(list(TAGLINES)), version=XONSH_VERSION)
for elem in WELCOME_MSG:
if isinstance(elem, str):
elem = (elem, "", "")
line = elem[0].format(**subst)
termwidth = os.get_terminal_size().columns
line = _align_string(line, elem[1], elem[2], width=termwidth)
print_color(line)
示例5: show
def show():
fig = plt.gcf()
w, h = shutil.get_terminal_size()
if ON_WINDOWS:
w -= 1 # @melund reports that win terminals are too thin
h -= 1 # leave space for next prompt
buf = figure_to_rgb_array(fig, w, h)
s = buf_to_color_str(buf)
print_color(s)
示例6: _colors
def _colors(ns):
cols, _ = shutil.get_terminal_size()
if ON_WINDOWS:
cols -= 1
cmap = color_style()
akey = next(iter(cmap))
if isinstance(akey, str):
s = _str_colors(cmap, cols)
else:
s = _tok_colors(cmap, cols)
print_color(s)
示例7: _pprint_displayhook
def _pprint_displayhook(value):
if value is not None:
builtins._ = None # Set '_' to None to avoid recursion
if HAVE_PYGMENTS:
s = pretty(value) # color case
lexer = pyghooks.XonshLexer()
tokens = list(pygments.lex(s, lexer=lexer))
print_color(tokens)
else:
pprint(value) # black & white case
builtins._ = value
示例8: _pprint_displayhook
def _pprint_displayhook(value):
if value is None or isinstance(value, HiddenCompletedCommand):
return
builtins._ = None # Set '_' to None to avoid recursion
if HAS_PYGMENTS:
s = pretty(value) # color case
lexer = pyghooks.XonshLexer()
tokens = list(pygments.lex(s, lexer=lexer))
print_color(tokens)
else:
pprint(value) # black & white case
builtins._ = value
示例9: trace
def trace(self, frame, event, arg):
"""Implements a line tracing function."""
if event not in self.valid_events:
return self.trace
fname = inspectors.find_file(frame)
if fname in self.files:
lineno = frame.f_lineno
curr = (fname, lineno)
if curr != self._last:
line = linecache.getline(fname, lineno).rstrip()
s = format_line(fname, lineno, line, color=self.usecolor, lexer=self.lexer, formatter=self.formatter)
print_color(s)
self._last = curr
return self.trace
示例10: _styles
def _styles(ns):
env = builtins.__xonsh_env__
curr = env.get('XONSH_COLOR_STYLE')
styles = sorted(color_style_names())
if ns.json:
s = json.dumps(styles, sort_keys=True, indent=1)
print(s)
return
lines = []
for style in styles:
if style == curr:
lines.append('* {GREEN}' + style + '{NO_COLOR}')
else:
lines.append(' ' + style)
s = '\n'.join(lines)
print_color(s)
示例11: _styles
def _styles(ns):
env = builtins.__xonsh__.env
curr = env.get("XONSH_COLOR_STYLE")
styles = sorted(color_style_names())
if ns.json:
s = json.dumps(styles, sort_keys=True, indent=1)
print(s)
return
lines = []
for style in styles:
if style == curr:
lines.append("* {GREEN}" + style + "{NO_COLOR}")
else:
lines.append(" " + style)
s = "\n".join(lines)
print_color(s)
示例12: source_alias
def source_alias(args, stdin=None):
"""Executes the contents of the provided files in the current context.
If sourced file isn't found in cwd, search for file along $PATH to source
instead.
"""
env = builtins.__xonsh__.env
encoding = env.get("XONSH_ENCODING")
errors = env.get("XONSH_ENCODING_ERRORS")
for i, fname in enumerate(args):
fpath = fname
if not os.path.isfile(fpath):
fpath = locate_binary(fname)
if fpath is None:
if env.get("XONSH_DEBUG"):
print("source: {}: No such file".format(fname), file=sys.stderr)
if i == 0:
raise RuntimeError(
"must source at least one file, " + fname + "does not exist."
)
break
_, fext = os.path.splitext(fpath)
if fext and fext != ".xsh" and fext != ".py":
raise RuntimeError(
"attempting to source non-xonsh file! If you are "
"trying to source a file in another language, "
"then please use the appropriate source command. "
"For example, source-bash script.sh"
)
with open(fpath, "r", encoding=encoding, errors=errors) as fp:
src = fp.read()
if not src.endswith("\n"):
src += "\n"
ctx = builtins.__xonsh__.ctx
updates = {"__file__": fpath, "__name__": os.path.abspath(fpath)}
with env.swap(**make_args_env(args[i + 1 :])), swap_values(ctx, updates):
try:
builtins.execx(src, "exec", ctx, filename=fpath)
except Exception:
print_color(
"{RED}You may be attempting to source non-xonsh file! "
"{NO_COLOR}If you are trying to source a file in "
"another language, then please use the appropriate "
"source command. For example, {GREEN}source-bash "
"script.sh{NO_COLOR}",
file=sys.stderr,
)
raise
示例13: show
def show():
'''Run the mpl display sequence by printing the most recent figure to console'''
try:
minimal = __xonsh_env__['XONTRIB_MPL_MINIMAL']
except KeyError:
minimal = XONTRIB_MPL_MINIMAL_DEFAULT
fig = plt.gcf()
if _use_iterm:
display_figure_with_iterm2(fig)
else:
# Display the image using terminal characters to fit into the console
w, h = shutil.get_terminal_size()
if ON_WINDOWS:
w -= 1 # @melund reports that win terminals are too thin
h -= 1 # leave space for next prompt
buf = figure_to_tight_array(fig, w, h, minimal)
s = buf_to_color_str(buf)
print_color(s)
示例14: _pprint_displayhook
def _pprint_displayhook(value):
if value is None:
return
builtins._ = None # Set '_' to None to avoid recursion
if isinstance(value, HiddenCommandPipeline):
builtins._ = value
return
env = builtins.__xonsh_env__
if env.get('PRETTY_PRINT_RESULTS'):
printed_val = pretty(value)
else:
printed_val = repr(value)
if HAS_PYGMENTS and env.get('COLOR_RESULTS'):
tokens = list(pygments.lex(printed_val, lexer=pyghooks.XonshLexer()))
print_color(tokens)
else:
print(printed_val) # black & white case
builtins._ = value
示例15: visit_load
def visit_load(self, node):
if node.check:
ap = 'Would you like to load an existing file, ' + YN
asker = TrueFalse(prompt=ap)
do_load = self.visit(asker)
if not do_load:
return Unstorable
fname = self.visit_input(node)
if fname is None or len(fname) == 0:
fname = node.default_file
if os.path.isfile(fname):
with open(fname, 'r') as f:
self.state = json.load(f)
print_color('{{GREEN}}{0!r} loaded.{{NO_COLOR}}'.format(fname))
else:
print_color(('{{RED}}{0!r} could not be found, '
'continuing.{{NO_COLOR}}').format(fname))
return fname