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))
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)
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 + "{RESET}") else: lines.append(" " + style) s = "\n".join(lines) print_color(s)
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! " "{RESET}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{RESET}", file=sys.stderr, ) raise
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)
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
def trace(self, frame, event, arg): """Implements a line tracing function.""" if event not in self.valid_events: return self.trace fname = 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 = tracer_format_line( fname, lineno, line, color=self.usecolor, lexer=self.lexer, formatter=self.formatter, ) print_color(s) self._last = curr return self.trace
def _pprint_displayhook(value): if value is None: return builtins._ = None # Set '_' to None to avoid recursion if isinstance(value, xpp.HiddenCommandPipeline): builtins._ = value return env = builtins.__xonsh__.env printed_val = None if env.get("PRETTY_PRINT_RESULTS"): printed_val = pretty(value) if not isinstance(printed_val, str): # pretty may fail (i.e for unittest.mock.Mock) 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_toolkit" else "\n" print_color(tokens, end=end) else: print(printed_val) # black & white case builtins._ = value
def _list(ns): """Lists xontribs.""" data = xontrib_data(ns) if ns.json: s = json.dumps(data) print(s) else: nname = max([6] + [len(x) for x in data]) s = "" for name, d in data.items(): lname = len(name) s += "{PURPLE}" + name + "{RESET} " + " " * (nname - lname) if d["installed"]: s += "{GREEN}installed{RESET} " else: s += "{RED}not-installed{RESET} " if d["loaded"]: s += "{GREEN}loaded{RESET}" else: s += "{RED}not-loaded{RESET}" s += "\n" print_color(s[:-1])
def dh_main_action(ns, hist=None, stdout=None, stderr=None): hd = HistoryDiffer(ns.a, ns.b, reopen=ns.reopen, verbose=ns.verbose) print_color(hd.format(), file=stdout)