Skip to content
Back to top
View this page
Edit this page

# xonsh.aliases

Aliases for the xonsh shell.

class xonsh.aliases.AliasReturnCommandResult(*args, local_env=None, **kwargs)

  List subclass that can carry local_env from return_command aliases.

  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.

  extend(iterable, /)

    Extend list by appending elements from the iterable.

  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.

  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.

  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.

  local_env: dict

class xonsh.aliases.Aliases(*args, **kwargs)

  Represents a location to hold and look up aliases.

  static capturable(f)

    Decorator that specifies that a callable alias should be run with capturing. This is the default behavior.

  static completer(completer_func)

    Decorator that attaches a completer function to an alias.

    Usage:

        def _my_completer(command, alias):
            return {'opt1', 'opt2'}

        @aliases.register
        @aliases.completer(_my_completer)
        def _hello(args):
            echo @(args)

    Now `hello <TAB>` will suggest `opt1` and `opt2`.

  static return_command(f)

    Decorator that switches alias from returning result to return in new command for execution.

  static threadable(f)

    Decorator that specifies that a callable alias should be run in a background thread. This is the default behavior.

  static uncapturable(f)

    Decorator that specifies that a callable alias should not be run with any capturing. This is often needed if the alias call interactive subprocess, like pagers and text editors.

  static unthreadable(f)

    Decorator that specifies that a callable alias should be run only on the main thread process. This is often needed for debuggers and profilers.

  clear() → None. Remove all items from D.
  eval_alias(value, seen_tokens=frozenset({}), acc_args=(), decorators=None, env_out=None)

    “Evaluates” the alias `value`, by recursively looking up the leftmost token and “expanding” if it’s also an alias.

    A value like `["cmd", "arg"]` might transform like this: `> ["cmd", "arg"] -> ["ls", "-al", "arg"] -> callable()` where `cmd=ls -al` and `ls` is an alias with its value being a callable. The resulting callable will be “partially applied” with `["-al", "arg"]`.

    `env_out`, if given, is a mutable dict that accumulates the env overlay requested by any `return_command` alias encountered while resolving the chain (via dict-return `"env"` key). The top-level `get()` caller passes its own collector dict here.

  expand_alias(line: str, cursor_index: int) → str

    Expands any aliases present in line if alias does not point to a builtin function and if alias is only a single command. The command won’t be expanded if the cursor’s inside/behind it.

  get(key, default=None, decorators=None)

    Returns list that represent command with resolved aliases. The `key` can be string with alias name or list for a command. In the first position will be the resolved command name or callable alias. If the key is not present, then default is returned.

    `decorators` is the list of DecoratorAlias objects that found during resolving aliases (#5443).

    Note! The return value is always list because during resolving we can find return_command alias that can completely replace command and add new arguments.

  get_doc(name: str) → str

    Return the cleaned docstring of an alias.

    Resolution order:

    1. An explicit doc set via the dict-form `aliases[k] = {"alias": ..., "doc": "..."}` takes priority over everything else — it’s the only way to attach a description to a list/string alias and an intentional override for callable aliases.

    2. For `FuncAlias` instances, the wrapped function’s `__doc__` (read from `alias.func` directly to avoid falling back to `FuncAlias.__doc__`, which would otherwise leak the class placeholder `"Provides a callable alias for xonsh commands."`).

    3. For any other alias object (e.g. `ArgParserAlias`, `ExecAlias`), the object’s own `__doc__`.

    4. List- and string-aliases without an explicit doc yield `""`.

    The returned string is run through `inspect.cleandoc()` so multi-line docstrings have shared indentation removed.

  items() → a set-like object providing a view on D's items
  keys() → a set-like object providing a view on D's keys
  pop(k[, d]) → v, remove specified key and return the corresponding

    value. If key is not found, d is returned if given, otherwise KeyError is raised.

  popitem() → (k, v), remove and return some (key, value) pair

    as a 2-tuple; but raise KeyError if D is empty.

  register(func: LambdaType) → LambdaType
  register(name: str, *, dash_case: bool = True) → Callable[[LambdaType], LambdaType]

    Decorator to register the given function by name.

  setdefault(k[, d]) → D.get(k,d), also set D[k]=d if k not in D
  update([E, ]**F) → None. Update D from mapping/iterable E and F.
    If E present and has a .keys() method, does:

      for k in E.keys(): D[k] = E[k]

    If E present and lacks .keys() method, does:

      for (k, v) in E: D[k] = v

    In either case, this is followed by:

      for k, v in F.items(): D[k] = v

  values() → an object providing a view on D's values

class xonsh.aliases.ExecAlias(src, filename='<exec-alias>')

  Provides an exec alias for xonsh source code.

  Parameters:
    src str

      Source code that will be

class xonsh.aliases.FuncAlias(name, func=None)

  Provides a callable alias for xonsh commands.

  attributes_inherit = ['__xonsh_threadable__', '__xonsh_capturable__', 'return_what', '__doc__']
  attributes_show = ['__xonsh_threadable__', '__xonsh_capturable__', 'return_what']
  return_what: Literal['command', 'result'] = 'result'

class xonsh.aliases.PartialEvalAlias(f, acc_args=())

  Partially evaluated alias.

  Wraps a callable alias with accumulated arguments. The wrapped function’s signature is inspected once at init time. At call time, arguments are matched by name (with positional fallback for unnamed parameters).

class xonsh.aliases.SourceForeignAlias(threadable=True, **kwargs)
  exception Error(message: str, errno=1)

    Special case, when raised, the traceback will not be shown. Instead the process with exit with error code and message

    add_note(note, /)

      Add a note to the exception

    with_traceback(tb, /)

      Set self.__traceback__ to tb and return self.

    args
  build()

    Sub-classes should return constructed ArgumentParser

  create_parser(func=None, has_args=False, allowed_params=None, **kwargs) → ArgParser

    create root parser

  err(*args, **kwargs)

    Write text to error stream

  out(*args, **kwargs)

    Write text to output stream

  write_to(stream: str, *args, **kwargs)
  xonsh_complete(command, **kwargs)
  property parser

xonsh.aliases.get_alias_name(name_or_func, dash_case=True)

  Derive an alias name from a function or a string.

  For functions, uses `__name__` with a single leading underscore stripped (so `_hello` becomes `hello`). Strings are used as-is. If `dash_case` is True, underscores are replaced with dashes.

xonsh.aliases.get_xpip_alias()

  Determines the correct invocation to get xonsh’s pip

xonsh.aliases.get_xxonsh_alias()

  Determine the correct invocation to launch xonsh the same way the current session was launched.

  Always returns a list, so the result can be concatenated with other argv lists (e.g. `['tmux', 'new-session'] + get_xxonsh_alias()`).

  For an entry-point launch (e.g. `/usr/local/bin/xonsh`) the value of `sys.argv[0]` is already a runnable absolute path, so the result is a single-element list.

  For a “from source” launch via `python -m xonsh` (`sys.argv[0]` basename is `__main__.py`) a naive `[sys.executable, "-m", "xonsh"]` would be CWD-dependent: `python -m xonsh` resolves the package via `sys.path`, which has the current working directory at position 0. Running `xxonsh` from outside the source repo would silently pick whatever `import xonsh` resolves to in `site-packages` (or raise `ModuleNotFoundError`), which is almost never what the user wants.

  Instead, compute the parent directory of the source `xonsh` package once (from the absolute path of `__main__.py`) and spawn Python with a `-c` bootstrap that prepends that directory to `sys.path` before importing `xonsh.main`. This makes the alias resolve to the same source tree from any CWD, regardless of what is installed in `site-packages`.

xonsh.aliases.make_default_aliases()

  Creates a new default aliases dictionary.

xonsh.aliases.partial_eval_alias(f, acc_args=())

  Wraps a callable alias with accumulated arguments.

xonsh.aliases.print_alias_help(name: str, superhelp: bool = False) → None

  Print info about an alias to the active shell.

  Used by the `cmd?`/`cmd??` subprocess-mode help syntax. Output is colorized via xonsh color tokens.

  Parameters:
    name

      Alias name (must be present in `XSH.aliases`).

    superhelp

      If True (`cmd??`), include docstring, threadable/capturable flags, source location and source code for `FuncAlias`.

xonsh.aliases.run_alias_by_params(func: Callable, params: dict[str, Any])

  Run alias function based on signature and params. If function param names are in alias signature fill them. If function params have unknown names fill using alias signature order.

xonsh.aliases.showcmd(args, stdin=None)

  usage: showcmd [-e|–expand-alias] [-h|–help] cmd

  Displays the command and arguments as a list of strings that xonsh would run in subprocess mode. This is useful for determining how xonsh evaluates your commands and arguments prior to running these commands.

  optional arguments:
    `-e, --expand-alias`

      expand alias

    `-h, --help`

      show this help message and exit

  Examples

  @ showcmd echo $USER “can’t” hear “the sea” [‘echo’, ‘I’, “can’t”, ‘hear’, ‘the sea’]

  @ aliases[‘ali’] = ‘echo 1’ @ showcmd -e ali 2 [‘echo’, ‘1’, ‘2’]

xonsh.aliases.source_alias_fn(files: Annotated[list[str], (), 'nargs', '+', 'completer', None], ignore_ext=False, _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.

  Parameters:
    files

      paths to source files.

    ignore_ext-e, –ignore-ext

      don’t check the file extension

xonsh.aliases.source_cmd_fn(files: Annotated[list[str], (), 'nargs', '+', 'completer', None], login=False, aliascmd=None, extra_args='', safe=True, postcmd='', funcscmd='', seterrprevcmd=None, overwrite_aliases=False, suppress_skip_message=False, show=False, show_output=False, dryrun=False, _stderr=None)

  > Source cmd.exe files

  Parameters:
    files

      paths to source files.

    login-l, –login

      whether the sourced shell should be login

    envcmd–envcmd

      command to print environment

    aliascmd–aliascmd

      command to print aliases

    extra_args–extra-args

      extra arguments needed to run the shell

    safe-s, –safe

      whether the source shell should be run safely, and not raise any errors, even if they occur.

    postcmd–postcmd

      command(s) to run after all other commands

    funcscmd–funcscmd

      code to find locations of all native functions in the shell language.

    seterrprevcmd–seterrprevcmd

      command(s) to set exit-on-error before any other commands.

    overwrite_aliases–overwrite-aliases

      flag for whether or not sourced aliases should replace the current xonsh aliases.

    suppress_skip_message–suppress-skip-message

      flag for whether or not skip messages should be suppressed.

    show–show

      show the generated shell command that will be sent to cmd.exe (does not show what the sourced script prints — see `--show-output` for that).

    show_output–show-output

      forward stdout and stderr produced by the sourced script to the xonsh terminal. By default they are silently discarded.

    dryrun-d, –dry-run

      Will not actually source the file.

xonsh.aliases.source_foreign_fn(shell: str, files_or_code: Annotated[list[str], (), 'nargs', '+', 'completer', None], interactive=False, login=False, envcmd=None, aliascmd=None, extra_args='', safe=True, prevcmd='', postcmd='', funcscmd='', sourcer=None, use_tmpfile=False, seterrprevcmd=None, seterrpostcmd=None, overwrite_aliases=False, suppress_skip_message=False, show=False, show_output=False, dryrun=False, _stderr=None)

  Sources a file written in a foreign shell language.

  Parameters:
    shell

      Name or path to the foreign shell

    files_or_code

      file paths to source or code in the target language.

    interactive-i, –interactive

      whether the sourced shell should be interactive

    login-l, –login

      whether the sourced shell should be login

    envcmd–envcmd

      command to print environment

    aliascmd–aliascmd

      command to print aliases

    extra_args–extra-args

      extra arguments needed to run the shell

    safe-u, –unsafe

      whether the source shell should be run safely, and not raise any errors, even if they occur.

    prevcmd-p, –prevcmd

      command(s) to run before any other commands, replaces traditional source.

    postcmd–postcmd

      command(s) to run after all other commands

    funcscmd–funcscmd

      code to find locations of all native functions in the shell language.

    sourcer–sourcer

      the source command in the target shell language. If this is not set, a default value will attempt to be looked up based on the shell name.

    use_tmpfile–use-tmpfile

      whether the commands for source shell should be written to a temporary file.

    seterrprevcmd–seterrprevcmd

      command(s) to set exit-on-error before any other commands.

    seterrpostcmd–seterrpostcmd

      command(s) to set exit-on-error after all other commands.

    overwrite_aliases–overwrite-aliases

      flag for whether or not sourced aliases should replace the current xonsh aliases.

    suppress_skip_message–suppress-skip-message

      flag for whether or not skip messages should be suppressed.

    show–show

      show the generated shell command that will be sent to the foreign shell (does not show what the sourced script prints — see `--show-output` for that).

    show_output–show-output

      forward stdout and stderr produced by the sourced script to the xonsh terminal. By default they are silently discarded.

    dryrun-d, –dry-run

      Will not actually source the file.

xonsh.aliases.trace(args, stdin=None, stdout=None, stderr=None, spec=None)

  Runs the xonsh tracer utility.

xonsh.aliases.win_sudo(args)

  Run a command with Windows UAC elevation.

  Registered as the `sudo` alias on Windows only when no `sudo` binary is found on `$PATH` (see issue #5706). Resolves the target via `xonsh.environ.locate_binary()` and re-launches it through `ShellExecuteEx` with the `runas` verb; `cmd.exe` built-ins (`dir`, `copy`, …) are dispatched via `cmd /D /C` from the current working directory. The elevated process opens in a new console and does not inherit standard streams, so its output is not piped back.

xonsh.aliases.xexec_fn(command: Annotated[list[str], (), 'nargs', '...', 'completer', None], login=False, clean=False, name='', _stdin=None)

  exec (also aliased as xexec) uses the os.execvpe() function to replace the xonsh process with the specified program.

  This provides the functionality of the bash ‘exec’ builtin:

      >>> exec bash -l -i
      bash $

  Parameters:
    command

      program to launch along its arguments

    login-l, –login

      the shell places a dash at the beginning of the zeroth argument passed to command to simulate login shell.

    clean-c, –clean

      causes command to be executed with an empty environment.

    name-a, –name

      the shell passes name as the zeroth argument to the executed command.

  Notes

  This command is not the same as the Python builtin function exec(). That function is for running Python code. This command, which shares the same name as the sh-lang statement, is for launching a command directly in the same process. In the event of a name conflict, please use the xexec command directly or dive into subprocess mode explicitly with ![exec command]. For more details, please see http://xon.sh/faq.html#exec.

xonsh.aliases.xonsh_exit(args, stdin=None)

  Sends signal to exit shell.

xonsh.aliases.xonsh_reset(args, stdin=None)

  Clears __xonsh__.ctx

xonsh.aliases.WINDOWS_CMD_ALIASES = frozenset({'cls', 'copy', 'del', 'dir', 'echo', 'erase', 'md', 'mkdir', 'mklink', 'move', 'rd', 'ren', 'rename', 'rmdir', 'time', 'type', 'vol'})

  Built-in commands of `cmd.exe` that xonsh borrows on Windows.