shell package

Subpackages

Submodules

shell.base module

class shell.base.BaseShell(*args, env: ~typing.Dict[str, ~typing.Any] = None, use_model=True, save_session_prehook=<function identity>, load_session_posthook=<function identity>, **kwds)[source]

Bases: Cmd2

Extend Cmd with various capabilities. This class is restricted to functionality that requires Cmd methods to be overrriden.

Features:

  • An environment with local and global variable scopes.

  • Save/load sessions.

  • Decoration with functions, both at runtime and compile time.

add_functions(functions: Dict[str, ShellFunction], group_key=None)[source]

Add functions to this instance at runtime. Use a key to select a group of functions.

Parameters

functionsdict

A dictionary of functions to add.

group_keystr

A key to select a group of functions.

add_special_function(char: str, method: Callable[[Cmd2, str], str])[source]
do_bool(args: str) str[source]
do_env(keys: str)[source]

Retrieve environment variables. Return all variables if no key is given.

do_float(args: str) str[source]
do_int(args: str) str[source]
do_not(args: str) str[source]
do_reload(_)[source]

Reload the current session.

do_save(_)[source]

Save the current session.

do_undo(_)[source]

Undo the previous command

do_unset(args: str)[source]

Unset keys

unset [KEY [KEY..]]
static get_method(method_suffix: str)[source]
init_current_scope()[source]
is_function(k: str) bool[source]

Check whether k is an existing function.

is_hidden_function(k: str) bool[source]

Check whether k is an existing hidden function.

is_inline_function(k: str) bool[source]

Check whether k is an existing inline (user-defined) function.

is_special_function(char: str) bool[source]

Check whether char is a special characters method

last_method()[source]

Find the method corresponding to the last command run in shell. It has the form: do_{cmd}

Return a the last method if it exists and None otherwise.

load_session(session: str, strict=True)[source]

Load a session.

arameters

sessionstr

The session file to load.

strictbool

If True, raise an error if the session file is not found.

postcmd(stop, _)[source]

Display the shell_ready_signal to indicate termination to a parent process.

remove_functions(group_key=None)[source]

Remove functions to this instance at runtime. Use a key to select a group of functions

reset_locals()[source]

Reset enviornment variables and the current working directory.

run_commands(ast: str, prev_result='', run=False)[source]
run_hidden_function(k: str, args)[source]

Run a hidden function. See base.is_hidden_function

run_special_function(k: str, args)[source]
save_session(session='.shell_session.json')[source]

Save the current session to disk.

try_load_session(session='.shell_session.json')[source]

Try to load a session. Ignore errors.

Parameters

sessionstr

The session file to load. If not given, use the default session.

shell.base.filter_private_keys(env: dict) dict[source]
shell.base.is_private(key: str) bool[source]
shell.base.is_public(key: str) bool[source]

shell.cmd2 module

class shell.cmd2.Cmd2(completekey='tab', stdin=None, stdout=None)[source]

Bases: Cmd

Extend cmd.Cmd with various capabilities. This class is restricted to functionality that requires Cmd methods to be overrriden.

Features:

  • Confirmation mode to allow a user to accept or decline commands.

  • Error handling.

  • I/O methods: cat, source, print, println, exit

  • String methods: echo, flatten

Methods:

cmdloop(): An interactive REPL.
onecmd(): Run commands ad-hoc.
completenames(text, *ignored)[source]

Conditionally override Cmd.completenames

completenames_options = []
default(line: str)[source]

Called on an input line when the command prefix is not recognized.

If this method is not overridden, it prints an error message and returns.

do_E(args)[source]

Show the last exception

do_cat(filenames: str)[source]

Concatenate and print files

do_echo(args)[source]

Mimic Bash’s print function.

do_exit(args)[source]

exit [code]

Wrapper for sys.exit(code) with default code: 0

do_fail(msg: str)[source]
do_flatten(args: str) str[source]

Convert a space-separated string to a newline-separates string.

do_print(args)[source]

Write to stdout

do_println(args)[source]

Write each word as a newline to stdout.

do_range(args: str) str[source]

range(start, stop, [step])

do_shell(args)[source]

System call. Alias for !cmd

do_source(filenames: str)[source]
ignore_invalid_syntax = False
intro = 'Press ctrl-d to exit, ctrl-c to cancel, ? for help, ! for shell interop.\n-->\n'
mode = 1
none(_: str) str[source]

Do nothing. Similar to util.none.

onecmd(line: str) bool[source]

Parse and run line. Returns 0 on success and None otherwise. May raises ShellSyntaxError.

Parameters

linestr

The commands to run

onecmd_inner(lines: str)[source]

A wrapper for onecmd that can be overridden.

Parameters

linesstr

The command to run

onecmd_prehook(line)[source]

Similar to cmd.precmd but executed before cmd.onecmd.

onecmd_raw(line: str, prev_result: str)[source]
prompt = '$ '
use_mode(mode: Mode)[source]
class shell.cmd2.Mode(value, names=None, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Enum

COMPILE = 2
REPL = 1
shell.cmd2.cat_file(filename: str) str[source]
shell.cmd2.run(shell, commands, filename, repl=True)[source]
shell.cmd2.run_command(command: str, shell: Cmd2, strict=None)[source]

Run a single command in using shell.

Parameters

strictbool

Raise exceptions when encountering invalid syntax.

shell.cmd2.run_commands_from_file(filename: str, shell: Cmd2)[source]
shell.cmd2.run_interactively(shell: Cmd2)[source]

shell.errors module

exception shell.errors.ShellError[source]

Bases: RuntimeError

exception shell.errors.ShellPipeError[source]

Bases: RuntimeError

exception shell.errors.ShellSyntaxError[source]

Bases: ShellError

shell.function module

class shell.function.InlineFunction(command: str, args: List[str], func_name: str, multiline: bool = False, line_indent: str = None, inner: List[str] = <factory>)[source]

Bases: object

args: List[str]
command: str
func_name: str
inner: List[str]
line_indent: str = None
multiline: bool = False
class shell.function.ShellFunction(func, func_name=None, synopsis: str = None, args: Dict[str, str] = None, doc: str = None)[source]

Bases: object

handle_exception()[source]
shell.function.scope() dict[source]

shell.shell module

class shell.shell.Shell(*args, env: ~typing.Dict[str, ~typing.Any] = None, use_model=True, save_session_prehook=<function identity>, load_session_posthook=<function identity>, **kwds)[source]

Bases: BaseShell

Extend BaseShell with a language model: Support multiline statements, pipes, conditions, variables and inline function definitions.

The language grammer is based on a BNF-based grammer, which is defined in shell.grammer.parser

The AST is implemented here: shell.ast

The language implementation is defined in shell.ast.

do_map(line='')[source]

Apply a function to each item. It can be used as prefix or infix operator.

Usage (prefix)

map f x y z

Usage (infix)

f x |> map g
f x |> map g $ a b
f x >>= g

If $ is present, then each line from stdin is inserted there. Otherwise each line is appended.

do_math(args: str) str[source]
foldr(commands: List[Term], prev_results: str, delimiter='\n')[source]
keyboard_interrupt()[source]
onecmd_inner(lines: str)[source]

Override BaseShell.onecmd_inner. Apply a language model iff self.use_model is True.

Parameters

linesstr

The input lines.

parse(results: str)[source]
run_commands(ast: Node, prev_result='', run=False)[source]
shell.shell.add_cli_args(parser: ArgumentParser)[source]
shell.shell.all_commands(shell: Shell)[source]
shell.shell.build(functions: Dict[str, ShellFunction] = None, completions: Dict[str, Callable] = None, instantiate=True) Shell[source]

Extend the class Shell and create an instance of it. Note that set_functions must be called before instantiating Shell.

shell.shell.has_input() bool[source]

Check whether CMD is not empty.

shell.shell.main(shell: Shell = None, functions: Dict[str, ShellFunction] = None, repl=True) Shell[source]
shell.shell.read_stdin()[source]
shell.shell.run_command(command='', shell: Shell = None, strict=None)[source]

Run a newline-separated string of commands.

Parameters

strictbool

Raise exceptions when encountering invalid syntax.

shell.shell.set_cli_args()[source]
shell.shell.set_completions(functions: ~typing.Dict[str, ~typing.Callable], shell=<class 'shell.shell.Shell'>)[source]
shell.shell.set_functions(functions: ~typing.Dict[str, ~mash.shell.function.ShellFunction], cls: ~cmd.Cmd = <class 'shell.shell.Shell'>) type[source]

Extend cls with a set of functions Note that this modifies the class Shell directly, rather than an instance.

shell.shell.setup(shell: Shell = None, functions: Dict[str, ShellFunction] = None, completions: Dict[str, Callable] = None) Tuple[Shell, List[str], str][source]

Setup an instance of Shell with any given cli options.

First initialize Shell with functions and completions. Then apply any relevant cli options.

shell.shell.sh_to_py(cmd: str)[source]

A wrapper for shell commands

shell.with_filesystem module

ABC

class shell.with_filesystem.ShellWithFileSystem(data={}, repository: FileSystem = None, **kwds)[source]

Bases: object

add_cd_alias(dirname: str)[source]
cd(*path: str)[source]

Change directory and finally reset the current directory. Stay in the current directory by default.

complete_cd(text, line, begidx, endidx)[source]

Filter the result of ls to match text.

default_method(dirname: str)[source]
foreach(*keys: str, delimiter='\n')[source]

List all objects in the dir associated with each possible path, recursively.

If the path refers to a directory, then return the path to each directory. Otherwise return a list of files.

E.g. do a listing of repository/users/{id}/email.

get(*path: str)[source]

Return the value of the file associated with path.

init_home(*path: List[str | int] | str | int)[source]
init_shell(*build_args, **build_kwds)[source]
new(*keys: str)[source]
pwd()[source]

Print the path to the current working directory

set(*args: str)[source]

Assign a value to the file k.

set_cd_aliases()[source]

Add do_{dirname} methods to self.shell for each sub-directory.

set_shell_completions(cls)[source]
unset_cd_aliases()[source]

Remove all custom do_{dirname} methods from self.shell.

update_prompt()[source]
use(*path: str)[source]

Access a directory. Change directory in REPL mode, otherwise return the directory.

Module contents

See shell