util

class invoke.util.ExceptionHandlingThread(**kwargs)

Thread handler making it easier for parent to handle thread exceptions.

Based in part on Fabric 1’s ThreadHandler. See also Fabric GH issue #204.

When used directly, can be used in place of a regular threading.Thread. If subclassed, the subclass must do one of:

  • supply target to __init__
  • define _run() instead of run()

This is because this thread’s entire point is to wrap behavior around the thread’s execution; subclasses could not redefine run() without breaking that functionality.

__init__(**kwargs)

Create a new exception-handling thread instance.

Takes all regular threading.Thread keyword arguments, via **kwargs for easier display of thread identity when raising captured exceptions.

exception()

If an exception occurred, return an ExceptionWrapper around it.

Returns:An ExceptionWrapper managing the result of sys.exc_info, if an exception was raised during thread execution. If no exception occurred, returns None instead.
is_dead

Returns True if not alive and has a stored exception.

Used to detect threads that have excepted & shut down.

invoke.util.encode_output(string, encoding)

Transform string-like object string into bytes via encoding.

Returns:A byte-string (str on Python 2, bytes on Python 3.)
invoke.util.has_fileno(stream)

Cleanly determine whether stream has a useful .fileno().

Note

This function helps determine if a given file-like object can be used with various terminal-oriented modules and functions such as select, termios, and tty. For most of those, a fileno is all that is required; they’ll function even if stream.isatty() is False.

Parameters:stream – A file-like object.
Returns:True if stream.fileno() returns an integer, False otherwise (this includes when stream lacks a fileno method).
invoke.util.isatty(stream)

Cleanly determine whether stream is a TTY.

Specifically, first try calling stream.isatty(), and if that fails (e.g. due to lacking the method entirely) fallback to os.isatty.

Note

Most of the time, we don’t actually care about true TTY-ness, but merely whether the stream seems to have a fileno (per has_fileno). However, in some cases (notably the use of pty.fork to present a local pseudoterminal) we need to tell if a given stream has a valid fileno but isn’t tied to an actual terminal. Thus, this function.

Parameters:stream – A file-like object.
Returns:A boolean depending on the result of calling .isatty() and/or os.isatty.
invoke.util.sort_names(names)

Sort task names by nesting depth & then as regular strings.

class invoke.util.ExceptionWrapper(kwargs, type, value, traceback)

A namedtuple wrapping a thread-borne exception & that thread’s arguments. Mostly used as an intermediate between ExceptionHandlingThread (which preserves initial exceptions) and ThreadException (which holds 1..N such exceptions, as typically multiple threads are involved.)