Tools (xonsh.tools)

Misc. xonsh tools.

The following implementations were forked from the IPython project:

Implementations:

  • decode()
  • encode()
  • cast_unicode()
  • safe_hasattr()
  • indent()
exception xonsh.tools.XonshError[source]
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

args
class xonsh.tools.CommandsCache[source]

A lazy cache representing the commands available on the file system.

isdisjoint(other)

Return True if two sets have a null intersection.

all_commands
class xonsh.tools.DefaultNotGivenType[source]

Singleton for representing when no default value is given.

class xonsh.tools.redirect_stderr(new_target)[source]

Context manager for temporarily redirecting stderr to another file.

class xonsh.tools.redirect_stdout(new_target)[source]

Context manager for temporarily redirecting stdout to another file:

# How to send help() to stderr
with redirect_stdout(sys.stderr):
    help(dir)

# How to write help() to a file
with open('help.txt', 'w') as f:
    with redirect_stdout(f):
        help(pow)

Mostly for backwards compatibility.

xonsh.tools.always_false(x)[source]

Returns False

xonsh.tools.always_true(x)[source]

Returns True

xonsh.tools.argvquote(arg, force=False)[source]

Returns an argument quoted in such a way that that CommandLineToArgvW on Windows will return the argument string unchanged. This is the same thing Popen does when supplied with an list of arguments. Arguments in a command line should be separated by spaces; this function does not add these spaces. This implementation follows the suggestions outlined here: https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/

xonsh.tools.backup_file(fname)[source]

Moves an existing file to a new name that has the current time right before the extension.

xonsh.tools.bool_or_int_to_str(x)[source]

Converts a boolean or integer to a string.

xonsh.tools.bool_seq_to_csv(x)[source]

Converts a sequence of bools to a comma-separated string.

xonsh.tools.bool_to_str(x)[source]

Converts a bool to an empty string if False and the string ‘1’ if True.

xonsh.tools.cast_unicode(s, encoding=None)[source]
xonsh.tools.check_for_partial_string(x)[source]

Returns the starting index (inclusive), ending index (exclusive), and starting quote string of the most recent Python string found in the input.

check_for_partial_string(x) -> (startix, endix, quote)

Parameters:

x : str

The string to be checked (representing a line of terminal input)

Returns:

startix : int (or None)

The index where the most recent Python string found started (inclusive), or None if no strings exist in the input

endix : int (or None)

The index where the most recent Python string found ended (exclusive), or None if no strings exist in the input OR if the input ended in the middle of a Python string

quote : str (or None)

A string containing the quote used to start the string (e.g., b”, ”, ‘’‘), or None if no string was found.

xonsh.tools.color_style()[source]

Returns the current color map.

xonsh.tools.color_style_names()[source]

Returns an iterable of all available style names.

xonsh.tools.command_not_found(cmd)[source]

Uses the debian/ubuntu command-not-found utility to suggest packages for a command that cannot currently be found.

xonsh.tools.csv_to_bool_seq(x)[source]

Takes a comma-separated string and converts it into a list of bools.

xonsh.tools.csv_to_set(x)[source]

Convert a comma-separated list of strings to a set of strings.

xonsh.tools.decode(s, encoding=None)[source]
xonsh.tools.dynamic_cwd_tuple_to_str(x)[source]

Convert a canonical cwd_width tuple to a string.

xonsh.tools.encode(u, encoding=None)[source]
xonsh.tools.ensure_int_or_slice(x)[source]

Makes sure that x is list-indexable.

xonsh.tools.ensure_string(x)[source]

Returns a string if x is not a string, and x if it already is.

xonsh.tools.env_path_to_str(x)[source]

Converts an environment path to a string by joining on the OS separator.

xonsh.tools.escape_windows_cmd_string(s)[source]

Returns a string that is usable by the Windows cmd.exe. The escaping is based on details here and emperical testing: http://www.robvanderwoude.com/escapechars.php

xonsh.tools.executables_in(path)[source]

Returns a generator of files in path that the user could execute.

xonsh.tools.expand_case_matching(s)[source]

Expands a string to a case insenstive globable string.

xonsh.tools.expand_gray_colors_for_cmd_exe(style_map)[source]

Expand the style’s gray scale color range. All gray scale colors has a tendency to map to the same default GRAY in cmd.exe.

xonsh.tools.expandvars(path)[source]

Expand shell variables of the forms $var, ${var} and %var%.

Unknown variables are left unchanged.

xonsh.tools.fallback(cond, backup)[source]

Decorator for returning the object if cond is true and a backup if cond is false.

xonsh.tools.find_next_break(line, mincol=0, lexer=None)[source]

Returns the column number of the next logical break in subproc mode. This function may be useful in finding the maxcol argument of subproc_toks().

xonsh.tools.format_color(string, **kwargs)[source]

Formats strings that may contain colors. This simply dispatches to the shell instances method of the same name. The results of this function should be directly usable by print_color().

xonsh.tools.get_sep()[source]

Returns the appropriate filepath separator char depending on OS and xonsh options set

xonsh.tools.globpath(s, ignore_case=False)[source]

Simple wrapper around glob that also expands home and env vars.

xonsh.tools.history_tuple_to_str(x)[source]

Converts a valid history tuple to a canonical string.

xonsh.tools.iglobpath(s, ignore_case=False)[source]

Simple wrapper around iglob that also expands home and env vars.

xonsh.tools.indent(instr, nspaces=4, ntabs=0, flatten=False)[source]

Indent a string a given number of spaces or tabstops.

indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.

Parameters:

instr : basestring

The string to be indented.

nspaces : int (default: 4)

The number of spaces to be indented.

ntabs : int (default: 0)

The number of tabs to be indented.

flatten : bool (default: False)

Whether to scrub existing indentation. If True, all lines will be aligned to the same indentation. If False, existing indentation will be strictly increased.

Returns:

outstr : string indented by ntabs and nspaces.

xonsh.tools.intensify_colors_for_cmd_exe(style_map, replace_colors=None)[source]

Returns a modified style to where colors that maps to dark colors are replaced with brighter versions. Also expands the range used by the gray colors

xonsh.tools.intensify_colors_on_win_setter(enable)[source]

Resets the style when setting the INTENSIFY_COLORS_ON_WIN environment variable.

xonsh.tools.is_bool(x)[source]

Tests if something is a boolean.

xonsh.tools.is_bool_or_int(x)[source]

Returns whether a value is a boolean or integer.

xonsh.tools.is_bool_seq(x)[source]

Tests if an object is a sequence of bools.

xonsh.tools.is_callable(x)[source]

Tests if something is callable

xonsh.tools.is_completions_display_value(x)[source]
xonsh.tools.is_dynamic_cwd_width(x)[source]

Determine if the input is a valid input for the DYNAMIC_CWD_WIDTH environement variable.

xonsh.tools.is_env_path(x)[source]

This tests if something is an environment path, ie a list of strings.

xonsh.tools.is_float(x)[source]

Tests if something is a float

xonsh.tools.is_history_tuple(x)[source]

Tests if something is a proper history value, units tuple.

xonsh.tools.is_int(x)[source]

Tests if something is an integer

xonsh.tools.is_string(x)[source]

Tests if something is a string

xonsh.tools.is_string_or_callable(x)[source]

Tests if something is a string or callable

xonsh.tools.is_string_set(x)[source]

Tests if something is a set

xonsh.tools.levenshtein(a, b, max_dist=inf)[source]

Calculates the Levenshtein distance between a and b.

xonsh.tools.normabspath(p)[source]

Retuns as normalized absolute path, namely, normcase(abspath(p))

xonsh.tools.on_main_thread()[source]

Checks if we are on the main thread or not.

xonsh.tools.print_color(string, **kwargs)[source]

Prints a string that may contain colors. This dispatched to the shell method of the same name. Colors will be formatted if they have not already been.

xonsh.tools.print_exception(msg=None)[source]

Print exceptions with/without traceback.

xonsh.tools.safe_hasattr(obj, attr)[source]

In recent versions of Python, hasattr() only catches AttributeError. This catches all errors.

xonsh.tools.set_to_csv(x)[source]

Convert a set of strings to a comma-separated list of strings.

xonsh.tools.setup_win_unicode_console(enable)[source]

“Enables or disables unicode display on windows.

xonsh.tools.str_to_env_path(x)[source]

Converts a string to an environment path, ie a list of strings, splitting on the OS separator.

xonsh.tools.subexpr_from_unbalanced(expr, ltok, rtok)[source]

Attempts to pull out a valid subexpression for unbalanced grouping, based on opening tokens, eg. ‘(‘, and closing tokens, eg. ‘)’. This does not do full tokenization, but should be good enough for tab completion.

xonsh.tools.subproc_toks(line, mincol=-1, maxcol=None, lexer=None, returnline=False)[source]

Excapsulates tokens in a source code line in a uncaptured subprocess ![] starting at a minimum column. If there are no tokens (ie in a comment line) this returns None.

xonsh.tools.suggest_commands(cmd, env, aliases)[source]

Suggests alternative commands given an environment and aliases.

xonsh.tools.suggestion_sort_helper(x, y)[source]

Returns a score (lower is better) for x based on how similar it is to y. Used to rank suggestions.

xonsh.tools.swap(namespace, name, value, default=NotImplemented)[source]

Swaps a current variable name in a namespace for another value, and then replaces it when the context is exited.

xonsh.tools.to_bool(x)[source]

“Converts to a boolean in a semantically meaningful way.

xonsh.tools.to_bool_or_break(x)[source]
xonsh.tools.to_bool_or_int(x)[source]

Converts a value to a boolean or an integer.

xonsh.tools.to_completions_display_value(x)[source]
xonsh.tools.to_dynamic_cwd_tuple(x)[source]

Convert to a canonical cwd_width tuple.

xonsh.tools.to_history_tuple(x)[source]

Converts to a canonincal history tuple.

xonsh.tools.HISTORY_UNITS = {'': ('commands', <class 'int'>), 'gig': ('b', <function <lambda> at 0x7f4c38607d90>), 'h': ('s', <function <lambda> at 0x7f4c38607a60>), 'megs': ('b', <function <lambda> at 0x7f4c38607d08>), 'hr': ('s', <function <lambda> at 0x7f4c38607a60>), 'years': ('s', <function <lambda> at 0x7f4c38607bf8>), 'day': ('s', <function <lambda> at 0x7f4c38607ae8>), 'kilobyte': ('b', <function <lambda> at 0x7f4c38607c80>), 'kilobytes': ('b', <function <lambda> at 0x7f4c38607c80>), 'commands': ('commands', <class 'int'>), 'files': ('files', <class 'int'>), 'months': ('s', <function <lambda> at 0x7f4c38607b70>), 'gb': ('b', <function <lambda> at 0x7f4c38607d90>), 'mb': ('b', <function <lambda> at 0x7f4c38607d08>), 'f': ('files', <class 'int'>), 'gigabytes': ('b', <function <lambda> at 0x7f4c38607d90>), 's': ('s', <class 'float'>), 'yr': ('s', <function <lambda> at 0x7f4c38607bf8>), 'gigs': ('b', <function <lambda> at 0x7f4c38607d90>), 'month': ('s', <function <lambda> at 0x7f4c38607b70>), 'byte': ('b', <class 'int'>), 'min': ('s', <function <lambda> at 0x7f4c386079d8>), 'c': ('commands', <class 'int'>), 'command': ('commands', <class 'int'>), 'b': ('b', <class 'int'>), 'terabytes': ('b', <function <lambda> at 0x7f4c38607e18>), 'megabyte': ('b', <function <lambda> at 0x7f4c38607d08>), 'meg': ('b', <function <lambda> at 0x7f4c38607d08>), 'megabytes': ('b', <function <lambda> at 0x7f4c38607d08>), 'days': ('s', <function <lambda> at 0x7f4c38607ae8>), 'second': ('s', <class 'float'>), 'cmd': ('commands', <class 'int'>), 'y': ('s', <function <lambda> at 0x7f4c38607bf8>), 'seconds': ('s', <class 'float'>), 'cmds': ('commands', <class 'int'>), 'gigabyte': ('b', <function <lambda> at 0x7f4c38607d90>), 'd': ('s', <function <lambda> at 0x7f4c38607ae8>), 'sec': ('s', <class 'float'>), 'year': ('s', <function <lambda> at 0x7f4c38607bf8>), 'yrs': ('s', <function <lambda> at 0x7f4c38607bf8>), 'kb': ('b', <function <lambda> at 0x7f4c38607c80>), 'tb': ('b', <function <lambda> at 0x7f4c38607e18>), 'hour': ('s', <function <lambda> at 0x7f4c38607a60>), 'm': ('s', <function <lambda> at 0x7f4c386079d8>), 'terabyte': ('b', <function <lambda> at 0x7f4c38607e18>), 'mon': ('s', <function <lambda> at 0x7f4c38607b70>), 'bytes': ('b', <class 'int'>), 'mins': ('s', <function <lambda> at 0x7f4c386079d8>), 'hours': ('s', <function <lambda> at 0x7f4c38607a60>)}

Maps lowercase unit names to canonical name and conversion utilities.

xonsh.tools.RE_BEGIN_STRING = re.compile('([bBrRuU]*("""|\'\'\'|"|\'))')

Regular expression matching the start of a string, including quotes and leading characters (r, b, or u)

xonsh.tools.RE_STRING_CONT = {'"': re.compile('((\\\\(.|\\n))|([^"\\\\]))*'), "'": re.compile("((\\\\(.|\\n))|([^'\\\\]))*"), '"""': re.compile('((\\\\(.|\\n))|([^"\\\\])|("(?!""))|\\n)*'), "'''": re.compile("((\\\\(.|\\n))|([^'\\\\])|('(?!''))|\\n)*")}

Dictionary mapping starting quote sequences to regular expressions that match the contents of a string beginning with those quotes (not including the terminating quotes)

xonsh.tools.RE_STRING_START = re.compile('[bBrRuU]*')

Regular expression matching the characters before the quotes when starting a string (r, b, or u, case insensitive)