Shell

class nutcli.shell.Shell(cwd=None, env=None, clear_env=False, shell=None, default_effect=Effect.SideEffect, logger=None, **kwargs)

Bases: object

Run commands in closed shell environment.

Example usage
sh = Shell()
sh('echo "Hello World!"')
sh(['/bin/bash', '-c', 'echo "Hello World!"'])
she('echo $HELLO', env={'HELLO': 'World!'})
Parameters
  • cwd (str, optional) – Default working directory, defaults to None (= current working directory)

  • env (dict of str:str, optional) – Additional environment values, defaults to None

  • clear_env (bool, optional) – If True, current shell environment is ignored, defaults to False

  • shell (list of str, optional) – Shell that will be used to execute commands, defaults to None (= [‘/bin/bash’, ‘-c’])

  • default_effect (Effect, optional) – Default execution effect, defaults to Effect.SideEffect

  • logger (logger, optional) – Logger, defaults to None (= nutcli.message)

Additional keyword arguments can be specified to be forwarded to subprocess.run() call as default values if not passed to command execution.

class Effect(value)

Bases: enum.Enum

Sometimes, it is desirable to produce some additional effect such as a log message when the command is run. These values control the effect.

Blank = 0

Nothing is done when the command is executed.

LogExecution = 1

Each call is logged into the information log if it is enabled in nutcli.decorators.LogExecution.

SideEffect = 2

Each call is logged into the information log if it is enabled in nutcli.decorators.LogExecution. And the command is not run at all if dry run is enabled in nutcli.decorators.SideEffect.

__call__(command, env=None, effect=None, dry_run_result=None, execution_message=None, **kwargs)

Execute shell command.

Parameters
  • command (str or list of str) – Command to execute

  • env (dict of str:str, optional) – Additional environment variables, defaults to None

  • effect (Effect, optional) – Execution effect, defaults to None (= value provided in constructor)

  • dry_run_result (any, optional) – Result for dry run call if effect is set to SideEffect, defaults to None

  • execution_message (str, optional) – Log execution message if effect is set to LogExecution or SideEffect, defaults to None

Raises
Returns

Shell result object.

Return type

ShellResult

Command may be either a list of command and its arguments or a string representing a full command line. If it is a list it is run as is via subproccess.run(), if it is a string it is run inside a shell as:

  • [shell, command], e.g. ['/bin/bash', '-c', command]

Additional keyword arguments can be specified to be forwarded to subprocess.run() call. By default text mode is set to true, therefore if you capture output via capture_output or other means, it is considered to be a text and is decoded as utf-8 text.

Common subprocess.run() arguments:

  • capture_output {bool} – Capture stdout and stderr.

  • cwd {string} – Change working directory.

  • timeout – timeout in seconds

Note

See python documentation for more:

clone()

Create a deep copy of self.

Returns:

ShellEnvironment – Self deep copy.

class nutcli.shell.ShellResult(rc, stdout=None, stderr=None)

Bases: object

Result of successful shell command execution.

Parameters
  • rc (Int) – Command return code

  • stdout (bytes or str) – Captured command standard output stream

  • stderr (bytes or str) – Captured command standard error stream.

class nutcli.shell.ShellEnvironment(clear_env=False)

Bases: object

Manage copy of shell environment.

Parameters

clear_env (bool, optional) – If True, current shell environment is ignored, defaults to False

set(env)

Add values to the environment.

Parameters

env (dict of str:str) – Additional environment.

Returns

self

Return type

ShellEnvironment

get()

Get new copy of this environment as a dictionary.

Returns

This environment as a dictionary

Return type

dict of str:str

get_overrides()

Get only values that were added to the original environment.

Returns

Additional environment as a dictionary

Return type

dict of str:str

clone()

Get a deep copy of this object.

Returns

Deep copy of self.

Return type

ShellEnvironment

class nutcli.shell.ShellOutputPipe(callback, as_pty=None, tty_size=None)

Bases: threading.Thread

Provide a pipe that calls a callback on each line produced by the shell command.

Example usage: Just print what we get
sh = Shell()
with ShellOutputPipe(print) as pipe:
    sh('echo "Hello World!"', stdout=pipe)

The pipe is automatically closed when the context is destroyed or when the object is finalized (garbage collected). You can use close() method to close it explicitly.

Note

If stdout is a terminal then new pseudo terminal is created unless set otherwise with as_pty parameter.

Parameters
  • callback (function) – Callback to call on each line of the output.

  • as_pty (bool, optional) – If True, pseudo terminal is created. If False, normal pipe is created. If None, pseudo terminal is created if stdout is a terminal.

  • tty_size (list of int) – Requested size of new pseudo terminal. defaults to None (= do not change)

Note

The format of tty_size is: [num_rows, num_cols]. If either is set to zero then the value is not changed.

close()

Close the pipe.

class nutcli.shell.ShellLoggerPipe(logger, split=False, as_pty=None)

Bases: object

Forward shell output to a logger.

Example usage
logger = logging.getLogger(__name__)
sh = Shell()
with ShellLoggerPipe(logger) as (stdout, stderr)):
    sh('echo "Hello World!"', stdout=stdout, stderr=stderr)

The pipe is automatically closed when the context is destroyed or when the object is finalized (garbage collected). You can use close() method to close it explicitly.

Note

Bz default, both stdout and stderr output is forwarded to logger.info() method. If you want to distinguish between these two and forward stderr output to logger.error() instead set split to True.

Note

If stdout (or stderr respectively) is a terminal then new pseudo terminal is created unless set otherwise with as_pty parameter.

Parameters
  • logger (logger) – The logger.

  • split (bool, optional) – If True, stderr output is send to logger.error instead of logger.info, defaults to False

  • as_pty (bool, optional) – If True, pseudo terminal is created. If False, normal pipe is created. If None, pseudo terminal is created if the target stream (stdout or stderr) is a terminal.

close()

Close the pipe.

exception nutcli.shell.ShellError(message, cmd, cwd, env, stdout, stderr)

Bases: Exception

Provide information about shell error.

Parameters
  • message (str) – Error message

  • cmd (str or list of str) – Failed command

  • cwd (str) – Command working directory

  • env (ShellEnvironment) – Command environment

  • stdout (bytes or str) – Captured command standard output stream

  • stderr (bytes or str) – Captured command standard error stream.

property pretty_message

Get formatted error message. It is returned as list of string where each item represents one line of the message.

Returns

Error message lines.

Return type

list of str

exception nutcli.shell.ShellCommandError(rc, cmd, cwd, env, stdout, stderr)

Bases: nutcli.shell.ShellError

Provide information about failed command.

Parameters
  • rc (int) – Command return code

  • cmd (str or list of str) – Failed command

  • cwd (str) – Command working directory

  • env (ShellEnvironment) – Command environment

  • stdout (bytes or str) – Captured command standard output stream

  • stderr (bytes or str) – Captured command standard error stream.

property pretty_message

Get formatted error message. It is returned as list of string where each item represents one line of the message.

Returns

Error message lines.

Return type

list of str

exception nutcli.shell.ShellTimeoutError(timeout, cmd, cwd, env, stdout, stderr)

Bases: nutcli.shell.ShellError

Provide information about command that did not end in set time.

Parameters
  • timeout (int) – Timeout value in seconds

  • cmd (str or list of str) – Failed command

  • cwd (str) – Command working directory

  • env (ShellEnvironment) – Command environment

  • stdout (bytes or str) – Captured command standard output stream

  • stderr (bytes or str) – Captured command standard error stream.

property pretty_message

Get formatted error message. It is returned as list of string where each item represents one line of the message.

Returns

Error message lines.

Return type

list of str