xonsh.built_ins

The xonsh built-ins.

Note that this module is named ‘built_ins’ so as not to be confused with the special Python builtins module.

class xonsh.built_ins.Cmd(xsh: XonshSession, *args: str, bg=False, redirects: dict[str, str] | None = None)[source]

A command group.

hide()[source]

dispatch ![]

obj()[source]

dispatch !()

out()[source]

dispatch $()

pipe(*args)[source]

combine $() | $[]

run()[source]

dispatch $[]

class xonsh.built_ins.DynamicAccessProxy(refname, objname)[source]

Proxies access dynamically.

Parameters:
refnamestr

‘.’-separated string that represents the new, reference name that the user will access.

objnamestr

‘.’-separated string that represents the name where the target object actually lives that refname points to.

class xonsh.built_ins.InlineImporter[source]

Inline importer allows to import and use module attribute or function in one line.

class xonsh.built_ins.XonshList(iterable=(), /)[source]

List subclass returned by glob operations with convenience methods.

All methods return XonshList, enabling chaining:

g`**/*.py`.files().sorted().paths()
append(object, /)

Append object to the end of the list.

clear(/)

Remove all items from list.

copy(/)

Return a shallow copy of the list.

count(value, /)

Return number of occurrences of value.

dirs()[source]

Keep only paths that are existing directories.

exists()[source]

Keep only paths that exist on disk.

extend(iterable, /)

Extend list by appending elements from the iterable.

files()[source]

Keep only paths that are existing files.

filter(func)[source]

Return a XonshList with only elements where func(elem) is truthy.

hidden()[source]

Keep only hidden files and directories. On Unix: names starting with ‘.’. On Windows: also FILE_ATTRIBUTE_HIDDEN.

index(value, start=0, stop=sys.maxsize, /)

Return first index of value.

Raises ValueError if the value is not present.

insert(index, object, /)

Insert object before index.

paths()[source]

Convert string elements to pathlib.Path objects.

pop(index=-1, /)

Remove and return item at index (default last).

Raises IndexError if list is empty or index is out of range.

remove(value, /)

Remove first occurrence of value.

Raises ValueError if the value is not present.

reverse(/)

Reverse IN PLACE.

select(n)[source]

Pick the n-th element from each tuple, skipping None values.

sort(*, key=None, reverse=False)

Sort the list in ascending order and return None.

The sort is in-place (i.e. the list itself is modified) and stable (i.e. the order of two equal elements is maintained).

If a key function is given, apply it once to each list item and sort them, ascending or descending, according to their function values.

The reverse flag can be set to sort in descending order.

sorted(key=None, reverse=False)[source]

Return a new sorted XonshList.

unique()[source]

Return a XonshList with duplicates removed, preserving order.

visible()[source]

Keep only visible (non-hidden) files and directories. On Unix: names not starting with ‘.’. On Windows: no FILE_ATTRIBUTE_HIDDEN.

class xonsh.built_ins.XonshPathLiteral(*args, **kwargs)[source]

Extension of pathlib.Path to support extended functionality.

classmethod cwd()

Return a new path pointing to the current working directory.

classmethod from_uri(uri)

Return a new path from the given ‘file’ URI.

classmethod home()

Return a new path pointing to expanduser(‘~’).

absolute()

Return an absolute version of this path No normalization or symlink resolution is performed.

Use resolve() to resolve symlinks and remove ‘..’ segments.

as_posix()

Return the string representation of the path with forward (/) slashes.

as_uri()

Return the path as a URI.

cd() XonshPathLiteralChangeDirectoryContextManager[source]

Returns context manager to change the directory e.g. with p'/tmp'.cd(): $[ls]

chmod(mode, *, follow_symlinks=True)[source]

Extension of pathlib.Path.chmod that returns self instead of None.

exists(*, follow_symlinks=True)

Whether this path exists.

This method normally follows symlinks; to check whether a symlink exists, add the argument follow_symlinks=False.

expanduser()

Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser)

full_match(pattern, *, case_sensitive=None)

Return True if this path matches the given glob-style pattern. The pattern is matched against the entire path.

glob(pattern, *, case_sensitive=None, recurse_symlinks=False)

Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given relative pattern.

group(*, follow_symlinks=True)

Return the group name of the file gid.

Make this path a hard link pointing to the same file as target.

Note the order of arguments (self, target) is the reverse of os.link’s.

is_absolute()

True if the path is absolute (has both a root and, if applicable, a drive).

is_block_device()

Whether this path is a block device.

is_char_device()

Whether this path is a character device.

is_dir(*, follow_symlinks=True)

Whether this path is a directory.

is_fifo()

Whether this path is a FIFO.

is_file(*, follow_symlinks=True)

Whether this path is a regular file (also True for symlinks pointing to regular files).

is_junction()

Whether this path is a junction.

is_mount()

Check if this path is a mount point

is_relative_to(other, /, *_deprecated)

Return True if the path is relative to another path or False.

is_reserved()

Return True if the path contains one of the special names reserved by the system, if any.

is_socket()

Whether this path is a socket.

Whether this path is a symbolic link.

iterdir()

Yield path objects of the directory contents.

The children are yielded in arbitrary order, and the special entries ‘.’ and ‘..’ are not included.

joinpath(*pathsegments)

Combine this path with one or several arguments, and return a new path representing either a subpath (if all arguments are relative paths) or a totally different path (if one of the arguments is anchored).

lchmod(mode)

Like chmod(), except if the path points to a symlink, the symlink’s permissions are changed, rather than its target’s.

lstat()

Like stat(), except if the path points to a symlink, the symlink’s status information is returned, rather than its target’s.

match(path_pattern, *, case_sensitive=None)

Return True if this path matches the given pattern. If the pattern is relative, matching is done from the right; otherwise, the entire path is matched. The recursive wildcard ‘**’ is not supported by this method.

mkdir(mode=511, parents=False, exist_ok=False)[source]

Extension of pathlib.Path.mkdir that returns self instead of None.

open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)

Open the file pointed to by this path and return a file object, as the built-in open() function does.

owner(*, follow_symlinks=True)

Return the login name of the file owner.

read_bytes()

Open the file in bytes mode, read it, and close the file.

read_text(encoding=None, errors=None, newline=None)

Open the file in text mode, read it, and close the file.

Return the path to which the symbolic link points.

relative_to(other, /, *_deprecated, walk_up=False)

Return the relative path to another path identified by the passed arguments. If the operation is not possible (because this is not related to the other path), raise ValueError.

The walk_up parameter controls whether .. may be used to resolve the path.

rename(target)

Rename this path to the target path.

The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.

Returns the new Path instance pointing to the target path.

replace(target)

Rename this path to the target path, overwriting if that path exists.

The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.

Returns the new Path instance pointing to the target path.

resolve(strict=False)

Make the path absolute, resolving all symlinks on the way and also normalizing it.

rglob(pattern, *, case_sensitive=None, recurse_symlinks=False)

Recursively yield all existing files (of any kind, including directories) matching the given relative pattern, anywhere in this subtree.

rmdir()

Remove this directory. The directory must be empty.

samefile(other_path)

Return whether other_path is the same or not as this file (as returned by os.path.samefile()).

stat(*, follow_symlinks=True)

Return the result of the stat() system call on this path, like os.stat() does.

Make this path a symlink pointing to the target path. Note the order of arguments (link, target) is the reverse of os.symlink.

touch(mode=438, exist_ok=True)[source]

Extension of pathlib.Path.touch that returns self instead of None.

Remove this file or link. If the path is a directory, use rmdir() instead.

walk(top_down=True, on_error=None, follow_symlinks=False)

Walk the directory tree from this directory, similar to os.walk().

with_name(name)

Return a new path with the file name changed.

with_segments(*pathsegments)

Construct a new path object from any number of path-like objects. Subclasses may override this method to customize how new path objects are created from methods like iterdir().

with_stem(stem)

Return a new path with the stem changed.

with_suffix(suffix)

Return a new path with the file suffix changed. If the path has no suffix, add given suffix. If the given suffix is an empty string, remove the suffix from the path.

write_bytes(data)

Open the file in bytes mode, write to it, and close the file.

write_text(data, encoding=None, errors=None, newline=None)

Open the file in text mode, write to it, and close the file.

property anchor

The concatenation of the drive and root, or ‘’.

property drive

The drive prefix (letter or UNC path), if any.

property name

The final path component, if any.

property parent

The logical parent of the path.

property parents

A sequence of this path’s logical parents.

parser = <module 'posixpath' (frozen)>
property parts

An object providing sequence-like access to the components in the filesystem path.

property root

The root of the path, if any.

property stem

The final path component, minus its last suffix.

property suffix

The final component’s last suffix, if any.

This includes the leading period. For example: ‘.txt’

property suffixes

A list of the final component’s suffixes, if any.

These include the leading periods. For example: [‘.tar’, ‘.gz’]

class xonsh.built_ins.XonshPathLiteralChangeDirectoryContextManager(path: XonshPathLiteral)[source]

Implements context manager to use in xonsh path literal.

class xonsh.built_ins.XonshSession[source]

All components defining a xonsh session.

Warning! If you use this object for any reason and access __xonsh__ or xonsh.built_ins.XSH attributes or functions, you do so at your own risk, as the internal contents and behavior of this object may change with any release. For repeatable use cases, find a way to improve XonshSessionInterface or xonsh.api.

Attributes:
exit: int or None

Session attribute. In case of integer value it signals xonsh to exit with returning this value as exit code.

cmd(*args: str, **kwargs)[source]
load(execer=None, ctx=None, inherit_env=True, save_origin_env=False, **kwargs)[source]

Loads the session with default values.

Parameters:
execerExecer, optional

Xonsh execution object, may be None to start

ctxMapping, optional

Context to start xonsh session with.

inherit_envbool

If True: inherit environment variables from os.environ. If False: use default values for environment variables and set $XONSH_ENV_INHERITED = False.

unload()[source]
property aliases
property completers

Returns a list of all available completers. Init when first accessing the attribute

property last
class xonsh.built_ins.XonshSessionInterface[source]

Xonsh Session Interface

Attributes:
envxonsh.environ.Env

A xonsh environment e.g. @.env.get(‘HOME’, ‘/tmp’).

historyxonsh.history.History

Xonsh history backend e.g. @.history[-1].cmd. See also history –help to manage history from command line.

impxonsh.built_ins.InlineImporter

The inline importer provides instant access to library functions and attributes e.g. @.imp.time.time().

lastcmdxonsh.procs.pipelines.CommandPipeline

Last executed subprocess-mode command pipeline e.g. @.lastcmd.rtn returns exit code.

env = None
history = None
imp: InlineImporter

Inline importer allows to import and use module attribute or function in one line.

lastcmd = None
xonsh.built_ins.builtin_cmd(name)[source]

Run a builtin name as a subprocess command if $XONSH_BUILTINS_TO_CMD is set and the name is a known command or alias. Otherwise return the builtin value.

xonsh.built_ins.call_macro(f, raw_args, glbs, locs)[source]

Calls a function as a macro, returning its result.

Parameters:
fcallable object

The function that is called as f(*args).

raw_argstuple of str

The str representation of arguments of that were passed into the macro. These strings will be parsed, compiled, evaled, or left as a string depending on the annotations of f.

glbsMapping

The globals from the call site.

locsMapping or None

The locals from the call site.

xonsh.built_ins.convert_macro_arg(raw_arg, kind, glbs, locs, *, name='<arg>', macroname='<macro>')[source]

Converts a string macro argument based on the requested kind.

Parameters:
raw_argstr

The str representation of the macro argument.

kindobject

A flag or type representing how to convert the argument.

glbsMapping

The globals from the call site.

locsMapping or None

The locals from the call site.

namestr, optional

The macro argument name.

macronamestr, optional

The name of the macro itself.

Returns:
The converted argument.
xonsh.built_ins.ensure_list_of_strs(x)[source]

Ensures that x is a list of strings.

xonsh.built_ins.ensure_str_or_callable(x)[source]

Ensures that x is single string or function.

xonsh.built_ins.enter_macro(obj, raw_block, glbs, locs)[source]

Prepares to enter a context manager macro by attaching the contents of the macro block, globals, and locals to the object. These modifications are made in-place and the original object is returned.

Parameters:
objcontext manager

The object that is about to be entered via a with-statement.

raw_blockstr

The str of the block that is the context body. This string will be parsed, compiled, evaled, or left as a string depending on the return annotation of obj.__enter__.

glbsMapping

The globals from the context site.

locsMapping or None

The locals from the context site.

Returns:
objcontext manager

The same context manager but with the new macro information applied.

xonsh.built_ins.eval_fstring_field(field)[source]

Evaluates the argument in Xonsh context.

xonsh.built_ins.get_default_builtins(execer=None)[source]
xonsh.built_ins.globsearch(s)[source]
xonsh.built_ins.helper(x, name='')[source]

Prints help about, and then returns that variable.

xonsh.built_ins.in_macro_call(f, glbs, locs)[source]

Attaches macro globals and locals temporarily to function as a context manager.

Parameters:
fcallable object

The function that is called as f(*args).

glbsMapping

The globals from the call site.

locsMapping or None

The locals from the call site.

xonsh.built_ins.list_of_list_of_strs_outer_product(x)[source]

Takes an outer product of a list of strings

xonsh.built_ins.list_of_strs_or_callables(x)[source]

Ensures that x is a list of strings or functions. This is called when using the @() operator to expand it’s content.

xonsh.built_ins.path_literal(s)[source]
xonsh.built_ins.pathsearch(func, s, pymode=False, pathobj=False)[source]

Takes a string and returns a list of file paths that match (regex, glob, or arbitrary search function). If pathobj=True, the return is a list of pathlib.Path objects instead of strings.

xonsh.built_ins.regexmatchsearch(s)[source]

Regex glob that returns match groups instead of paths.

xonsh.built_ins.regexsearch(s)[source]
xonsh.built_ins.reglob(path, parts=None, i=None, include_dotfiles=False)[source]

Regular expression-based globbing.

xonsh.built_ins.resetting_signal_handle(sig, f)[source]

Sets a new signal handle that will automatically restore the old value once the new handle is finished.

xonsh.built_ins.subproc_captured_hiddenobject(*cmds, envs=None, in_boolop=False)[source]

Runs a subprocess, capturing the output. Returns an instance of HiddenCommandPipeline representing the completed command.

xonsh.built_ins.subproc_captured_inject(*cmds, envs=None, in_boolop=False)[source]

Runs a subprocess, capturing the output. Returns a list of whitespace-separated strings of the stdout that was produced. The string is split using xonsh’s lexer, rather than Python’s str.split() or shlex.split().

xonsh.built_ins.subproc_captured_object(*cmds, envs=None, in_boolop=False)[source]

Runs a subprocess, capturing the output. Returns an instance of CommandPipeline representing the completed command.

xonsh.built_ins.subproc_captured_stdout(*cmds, envs=None, in_boolop=False)[source]

Runs a subprocess, capturing the output. Returns the stdout that was produced as a str or list based on $XONSH_SUBPROC_OUTPUT_FORMAT.

in_boolop is set by the parser to True when this call is a direct operand of a &&/|| chain, so the runtime can adjust behavior (e.g. suppress $XONSH_SUBPROC_CMD_RAISE_ERROR to let the chain short-circuit on returncode).

xonsh.built_ins.subproc_check_boolop(value)[source]

Raise CalledProcessError if value is the (final) result of a subproc statement that ended in failure.

Used as the AST wrapper around two kinds of nodes:

  • The outermost BoolOp of a logical chain (cmd1 && cmd2 / cmd1 || cmd2). Python and/or short-circuits to the pipeline that determined the chain result, so the wrapper sees the final pipeline.

  • A standalone subproc-helper call at statement level — bare commands, ![...], $[...], $(...), @$(...). The explicit-capture form !(...) is intentionally not wrapped: per spec it is the user’s full responsibility.

When $XONSH_SUBPROC_RAISE_ERROR is True (default), this enforces “raise on the last executed pipeline’s non-zero exit code” semantics:

  • ls nono (standalone) — rc≠0: raises.

  • $(ls nono) (standalone) — rc≠0: raises.

  • $[ls nono] (standalone) — rc≠0: raises.

  • echo 1 && echo 2 — last is echo 2 (rc=0): no raise.

  • ls nono || echo 1 — last is echo 1 (rc=0): no raise.

  • ls nono && echo 1 — last is ls nono (rc≠0): raises.

Per-command overrides:

  • @error_ignore (spec.raise_subproc_error is False) on the final pipeline suppresses the raise — used e.g. for echo 1 && @error_ignore ls nono.

  • @error_raise raises directly at the pipeline level, so the wrapper never sees a failed value.

Some subproc helpers ($(), $[], @$()) return a string / None / list rather than a CommandPipeline, so the wrapper can’t read returncode directly off value. In that case it falls back to XSH.lastcmd — the most recently completed pipeline, which is the one this helper just ran.

xonsh.built_ins.subproc_uncaptured(*cmds, envs=None, in_boolop=False)[source]

Runs a subprocess, without capturing the output. Returns the stdout that was produced as a str.

xonsh.built_ins.superhelper(x, name='')[source]

Prints help about, and then returns that variable.

xonsh.built_ins.xonsh_builtins(execer=None)[source]

A context manager for using the xonsh builtins only in a limited scope. Likely useful in testing.