本文整理汇总了Python中xonsh.tools.print_color函数的典型用法代码示例。如果您正苦于以下问题:Python print_color函数的具体用法?Python print_color怎么用?Python print_color使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了print_color函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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))
开发者ID:BlaXpirit,项目名称:xonsh,代码行数:59,代码来源:inspectors.py
示例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)
开发者ID:gitter-badger,项目名称:xonsh,代码行数:9,代码来源:xonfig.py
示例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)
开发者ID:Carreau,项目名称:xonsh,代码行数:9,代码来源:environ.py
示例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)
开发者ID:ericmharris,项目名称:xonsh,代码行数:9,代码来源:xonfig.py
示例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)
开发者ID:Cheaterman,项目名称:xonsh,代码行数:9,代码来源:mplhooks.py
示例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)
开发者ID:Siecje,项目名称:xonsh,代码行数:11,代码来源:xonfig.py
示例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
开发者ID:gitter-badger,项目名称:xonsh,代码行数:11,代码来源:main.py
示例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
开发者ID:aterrel,项目名称:xonsh,代码行数:12,代码来源:main.py
示例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
开发者ID:asmeurer,项目名称:xonsh,代码行数:14,代码来源:tracer.py
示例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)
开发者ID:Siecje,项目名称:xonsh,代码行数:16,代码来源:xonfig.py
示例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)
开发者ID:ericmharris,项目名称:xonsh,代码行数:16,代码来源:xonfig.py
示例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
开发者ID:ericmharris,项目名称:xonsh,代码行数:47,代码来源:aliases.py
示例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)
开发者ID:VHarisop,项目名称:xonsh,代码行数:18,代码来源:mplhooks.py
示例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
开发者ID:vsajip,项目名称:xonsh,代码行数:18,代码来源:main.py
示例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
开发者ID:BlaXpirit,项目名称:xonsh,代码行数:18,代码来源:wizard.py
示例16: _colors
def _colors(args):
columns, _ = shutil.get_terminal_size()
columns -= int(ON_WINDOWS)
style_stash = builtins.__xonsh_env__["XONSH_COLOR_STYLE"]
if args.style is not None:
if args.style not in color_style_names():
print("Invalid style: {}".format(args.style))
return
builtins.__xonsh_env__["XONSH_COLOR_STYLE"] = args.style
color_map = color_style()
akey = next(iter(color_map))
if isinstance(akey, str):
s = _str_colors(color_map, columns)
else:
s = _tok_colors(color_map, columns)
print_color(s)
builtins.__xonsh_env__["XONSH_COLOR_STYLE"] = style_stash
开发者ID:Carreau,项目名称:xonsh,代码行数:19,代码来源:xonfig.py
示例17: _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()))
end = "" if env.get("SHELL_TYPE") == "prompt_toolkit2" else "\n"
print_color(tokens, end=end)
else:
print(printed_val) # black & white case
builtins._ = value
开发者ID:mitnk,项目名称:xonsh,代码行数:19,代码来源:main.py
示例18: 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(ARGS=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
开发者ID:VHarisop,项目名称:xonsh,代码行数:41,代码来源:aliases.py
示例19: _list
def _list(ns):
"""Lists xontribs."""
meta = xontrib_metadata()
data = []
nname = 6 # ensures some buffer space.
names = None if len(ns.names) == 0 else set(ns.names)
for md in meta['xontribs']:
name = md['name']
if names is not None and md['name'] not in names:
continue
nname = max(nname, len(name))
spec = find_xontrib(name)
if spec is None:
installed = loaded = False
else:
installed = True
loaded = spec.name in sys.modules
d = {'name': name, 'installed': installed, 'loaded': loaded}
data.append(d)
if ns.json:
jdata = {d.pop('name'): d for d in data}
s = json.dumps(jdata)
print(s)
else:
s = ""
for d in data:
name = d['name']
lname = len(name)
s += "{PURPLE}" + name + "{NO_COLOR} " + " "*(nname - lname)
if d['installed']:
s += '{GREEN}installed{NO_COLOR} '
else:
s += '{RED}not-installed{NO_COLOR} '
if d['loaded']:
s += '{GREEN}loaded{NO_COLOR}'
else:
s += '{RED}not-loaded{NO_COLOR}'
s += '\n'
print_color(s[:-1])
开发者ID:laerus,项目名称:xonsh,代码行数:39,代码来源:xontribs.py
示例20: _list
def _list(ns):
"""Lists xontribs."""
meta = xontrib_metadata()
data = []
nname = 6 # ensures some buffer space.
names = None if len(ns.names) == 0 else set(ns.names)
for md in meta["xontribs"]:
name = md["name"]
if names is not None and md["name"] not in names:
continue
nname = max(nname, len(name))
spec = find_xontrib(name)
if spec is None:
installed = loaded = False
else:
installed = True
loaded = spec.name in sys.modules
d = {"name": name, "installed": installed, "loaded": loaded}
data.append(d)
if ns.json:
jdata = {d.pop("name"): d for d in data}
s = json.dumps(jdata)
print(s)
else:
s = ""
for d in data:
name = d["name"]
lname = len(name)
s += "{PURPLE}" + name + "{NO_COLOR} " + " " * (nname - lname)
if d["installed"]:
s += "{GREEN}installed{NO_COLOR} "
else:
s += "{RED}not-installed{NO_COLOR} "
if d["loaded"]:
s += "{GREEN}loaded{NO_COLOR}"
else:
s += "{RED}not-loaded{NO_COLOR}"
s += "\n"
print_color(s[:-1])
开发者ID:donnemartin,项目名称:gitsome,代码行数:39,代码来源:xontribs.py
注:本文中的xonsh.tools.print_color函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论