class documentation

Context-aware API wrapper & state-passing object. `.Context` objects are created during command-line parsing (or, if desired, by hand) and used to share parser and configuration state with executed tasks (see :ref:`why-context`). Specifically, the class offers wrappers for core API calls (such as `.run`) which take into account CLI parser flags, configuration files, and/or changes made at runtime. It also acts as a proxy for its `~.Context.config` attribute - see that attribute's documentation for details. Instances of `.Context` may be shared between tasks when executing sub-tasks - either the same context the caller was given, or an altered copy thereof (or, theoretically, a brand new one). .. versionadded:: 1.0

Method __init__ :param config: `.Config` object to use as the base configuration.
Method cd Context manager that keeps directory state when executing commands.
Method config.setter Undocumented
Method prefix Prefix all nested `run`/`sudo` commands with given command plus ``&&``.
Method run Execute a local shell command, honoring config options.
Method sudo Execute a shell command via ``sudo`` with password auto-response.
Property config Undocumented
Property cwd Return the current working directory, accounting for uses of `cd`.
Method _prefix_commands Prefixes ``command`` with all prefixes found in ``command_prefixes``.
Method _run Undocumented
Method _sudo Undocumented

Inherited from DataProxy:

Class Method from_data Alternate constructor for 'baby' DataProxies used as sub-dict values.
Method __contains__ Undocumented
Method __delattr__ Undocumented
Method __delitem__ Undocumented
Method __eq__ Undocumented
Method __getattr__ Undocumented
Method __getitem__ Undocumented
Method __iter__ Undocumented
Method __len__ Undocumented
Method __repr__ Undocumented
Method __setattr__ Undocumented
Method __setitem__ Undocumented
Method clear Undocumented
Method pop Undocumented
Method popitem Undocumented
Method setdefault Undocumented
Method update Undocumented
Method _get Undocumented
Method _set Convenience workaround of default 'attrs are config keys' behavior.
Method _track_modification_of Undocumented
Method _track_removal_of Undocumented
Class Variable _proxies Undocumented
Property _is_leaf Undocumented
Property _is_root Undocumented
def __init__(self, config=None): (source)

:param config: `.Config` object to use as the base configuration. Defaults to an anonymous/default `.Config` instance.

@contextmanager
def cd(self, path): (source)

Context manager that keeps directory state when executing commands. Any calls to `run`, `sudo`, within the wrapped block will implicitly have a string similar to ``"cd <path> && "`` prefixed in order to give the sense that there is actually statefulness involved. Because use of `cd` affects all such invocations, any code making use of the `cwd` property will also be affected by use of `cd`. Like the actual 'cd' shell builtin, `cd` may be called with relative paths (keep in mind that your default starting directory is your user's ``$HOME``) and may be nested as well. Below is a "normal" attempt at using the shell 'cd', which doesn't work since all commands are executed in individual subprocesses -- state is **not** kept between invocations of `run` or `sudo`:: c.run('cd /var/www') c.run('ls') The above snippet will list the contents of the user's ``$HOME`` instead of ``/var/www``. With `cd`, however, it will work as expected:: with c.cd('/var/www'): c.run('ls') # Turns into "cd /var/www && ls" Finally, a demonstration (see inline comments) of nesting:: with c.cd('/var/www'): c.run('ls') # cd /var/www && ls with c.cd('website1'): c.run('ls') # cd /var/www/website1 && ls .. note:: Space characters will be escaped automatically to make dealing with such directory names easier. .. versionadded:: 1.0 .. versionchanged:: 1.5 Explicitly cast the ``path`` argument (the only argument) to a string; this allows any object defining ``__str__`` to be handed in (such as the various ``Path`` objects out there), and not just string literals.

@config.setter
def config(self, value): (source)

Undocumented

@contextmanager
def prefix(self, command): (source)

Prefix all nested `run`/`sudo` commands with given command plus ``&&``. Most of the time, you'll want to be using this alongside a shell script which alters shell state, such as ones which export or alter shell environment variables. For example, one of the most common uses of this tool is with the ``workon`` command from `virtualenvwrapper <https://virtualenvwrapper.readthedocs.io/en/latest/>`_:: with c.prefix('workon myvenv'): c.run('./manage.py migrate') In the above snippet, the actual shell command run would be this:: $ workon myvenv && ./manage.py migrate This context manager is compatible with `cd`, so if your virtualenv doesn't ``cd`` in its ``postactivate`` script, you could do the following:: with c.cd('/path/to/app'): with c.prefix('workon myvenv'): c.run('./manage.py migrate') c.run('./manage.py loaddata fixture') Which would result in executions like so:: $ cd /path/to/app && workon myvenv && ./manage.py migrate $ cd /path/to/app && workon myvenv && ./manage.py loaddata fixture Finally, as alluded to above, `prefix` may be nested if desired, e.g.:: with c.prefix('workon myenv'): c.run('ls') with c.prefix('source /some/script'): c.run('touch a_file') The result:: $ workon myenv && ls $ workon myenv && source /some/script && touch a_file Contrived, but hopefully illustrative. .. versionadded:: 1.0

def run(self, command, **kwargs): (source)

Execute a local shell command, honoring config options. Specifically, this method instantiates a `.Runner` subclass (according to the ``runner`` config option; default is `.Local`) and calls its ``.run`` method with ``command`` and ``kwargs``. See `.Runner.run` for details on ``command`` and the available keyword arguments. .. versionadded:: 1.0

def sudo(self, command, **kwargs): (source)

Execute a shell command via ``sudo`` with password auto-response. **Basics** This method is identical to `run` but adds a handful of convenient behaviors around invoking the ``sudo`` program. It doesn't do anything users could not do themselves by wrapping `run`, but the use case is too common to make users reinvent these wheels themselves. .. note:: If you intend to respond to sudo's password prompt by hand, just use ``run("sudo command")`` instead! The autoresponding features in this method will just get in your way. Specifically, `sudo`: * Places a `.FailingResponder` into the ``watchers`` kwarg (see :doc:`/concepts/watchers`) which: * searches for the configured ``sudo`` password prompt; * responds with the configured sudo password (``sudo.password`` from the :doc:`configuration </concepts/configuration>`); * can tell when that response causes an authentication failure (e.g. if the system requires a password and one was not configured), and raises `.AuthFailure` if so. * Builds a ``sudo`` command string using the supplied ``command`` argument, prefixed by various flags (see below); * Executes that command via a call to `run`, returning the result. **Flags used** ``sudo`` flags used under the hood include: - ``-S`` to allow auto-responding of password via stdin; - ``-p <prompt>`` to explicitly state the prompt to use, so we can be sure our auto-responder knows what to look for; - ``-u <user>`` if ``user`` is not ``None``, to execute the command as a user other than ``root``; - When ``-u`` is present, ``-H`` is also added, to ensure the subprocess has the requested user's ``$HOME`` set properly. **Configuring behavior** There are a couple of ways to change how this method behaves: - Because it wraps `run`, it honors all `run` config parameters and keyword arguments, in the same way that `run` does. - Thus, invocations such as ``c.sudo('command', echo=True)`` are possible, and if a config layer (such as a config file or env var) specifies that e.g. ``run.warn = True``, that too will take effect under `sudo`. - `sudo` has its own set of keyword arguments (see below) and they are also all controllable via the configuration system, under the ``sudo.*`` tree. - Thus you could, for example, pre-set a sudo user in a config file; such as an ``invoke.json`` containing ``{"sudo": {"user": "someuser"}}``. :param str password: Runtime override for ``sudo.password``. :param str user: Runtime override for ``sudo.user``. .. versionadded:: 1.0

Undocumented

Return the current working directory, accounting for uses of `cd`. .. versionadded:: 1.0

def _prefix_commands(self, command): (source)

Prefixes ``command`` with all prefixes found in ``command_prefixes``. ``command_prefixes`` is a list of strings which is modified by the `prefix` context manager.

def _run(self, runner, command, **kwargs): (source)

Undocumented

def _sudo(self, runner, command, **kwargs): (source)

Undocumented