runners¶
-
class
invoke.runners.Runner(context)¶ Partially-abstract core command-running API.
This class is not usable by itself and must be subclassed, implementing a number of methods such as
start,waitandreturncode. For a subclass implementation example, see the source code forLocal.-
__init__(context)¶ Create a new runner with a handle on some
Context.Parameters: context – a
Contextinstance, used to transmit default options and provide access to other contextualized information (e.g. a remote-orientedRunnermight want aContextsubclass holding info about hostnames and ports.)Note
The
Contextgiven toRunnerinstances must contain default config values for theRunnerclass in question. At a minimum, this means values for each of the defaultRunner.runkeyword arguments such asechoandwarn.Raises: exceptions.ValueError – if not all expected default values are found in context.
-
program_finished= None¶ A
threading.Eventsignaling program completion.Typically set after
waitreturns. Some IO mechanisms rely on this to know when to exit an infinite read loop.
-
read_chunk_size= 1000¶ How many bytes (at maximum) to read per iteration of stream reads.
-
input_sleep= 0.01¶ How many seconds to sleep on each iteration of the stdin read loop and other otherwise-fast loops.
-
warned_about_pty_fallback= None¶ Whether pty fallback warning has been emitted.
-
watchers= None¶ A list of
StreamWatcherinstances for use byrespond. Is filled in at runtime byrun.
-
run(command, **kwargs)¶ Execute
command, returning an instance ofResult.Note
All kwargs will default to the values found in this instance’s
contextattribute, specifically in its configuration’srunsubtree (e.g.run.echoprovides the default value for theechokeyword, etc). The base default values are described in the parameter list below.Parameters: - command (str) – The shell command to execute.
- shell (str) – Which shell binary to use. Default:
/bin/bash. - warn (bool) –
Whether to warn and continue, instead of raising
UnexpectedExit, when the executed command exits with a nonzero status. Default:False.Note
This setting has no effect on exceptions, which will still be raised, typically bundled in
ThreadExceptionobjects if they were raised by the IO worker threads.Similarly,
WatcherErrorexceptions raised byStreamWatcherinstances will also ignore this setting, and will usually be bundled insideFailureobjects (in order to preserve the execution context). - hide –
Allows the caller to disable
run’s default behavior of copying the subprocess’ stdout and stderr to the controlling terminal. Specifyhide='out'(or'stdout') to hide only the stdout stream,hide='err'(or'stderr') to hide only stderr, orhide='both'(orTrue) to hide both streams.The default value is
None, meaning to print everything;Falsewill also disable hiding.Note
Stdout and stderr are always captured and stored in the
Resultobject, regardless ofhide’s value.Note
hide=Truewill also overrideecho=Trueif both are given (either as kwargs or via config/CLI). - pty (bool) –
By default,
runconnects directly to the invoked process and reads its stdout/stderr streams. Some programs will buffer (or even behave) differently in this situation compared to using an actual terminal or pseudoterminal (pty). To use a pty instead of the default behavior, specifypty=True.Warning
Due to their nature, ptys have a single output stream, so the ability to tell stdout apart from stderr is not possible when
pty=True. As such, all output will appear onout_stream(see below) and be captured into thestdoutresult attribute.err_streamandstderrwill always be empty whenpty=True. - fallback (bool) – Controls auto-fallback behavior re: problems offering a pty when
pty=True. Whether this has any effect depends on the specificRunnersubclass being invoked. Default:True. - echo (bool) –
Controls whether
runprints the command string to local stdout prior to executing it. Default:False.Note
hide=Truewill overrideecho=Trueif both are given. - env (dict) –
By default, subprocesses recieve a copy of Invoke’s own environment (i.e.
os.environ). Supply a dict here to update that child environment.For example,
run('command', env={'PYTHONPATH': '/some/virtual/env/maybe'})would modify thePYTHONPATHenv var, with the rest of the child’s env looking identical to the parent.See also
replace_envfor changing ‘update’ to ‘replace’. - replace_env (bool) – When
True, causes the subprocess to receive the dictionary given toenvas its entire shell environment, instead of updating a copy ofos.environ(which is the default behavior). Default:False. - encoding (str) – Override auto-detection of which encoding the subprocess is using
for its stdout/stderr streams (which defaults to the return value
of
default_encoding). - out_stream – A file-like stream object to which the subprocess’ standard output
should be written. If
None(the default),sys.stdoutwill be used. - err_stream – Same as
out_stream, except for standard error, and defaulting tosys.stderr. - in_stream –
A file-like stream object to used as the subprocess’ standard input. If
None(the default),sys.stdinwill be used.If
False, will disable stdin mirroring entirely (though other functionality which writes to the subprocess’ stdin, such as autoresponding, will still function.) Disabling stdin mirroring can help whensys.stdinis a misbehaving non-stream object, such as under test harnesses or headless command runners. - watchers (list) –
A list of
StreamWatcherinstances which will be used to scan the program’sstdoutorstderrand may write into itsstdin(typicallystrorbytesobjects depending on Python version) in response to patterns or other heuristics.See Automatically responding to program output for details on this functionality.
Default:
[]. - echo_stdin (bool) –
Whether to write data from
in_streamback toout_stream.In other words, in normal interactive usage, this parameter controls whether Invoke mirrors what you type back to your terminal.
By default (when
None), this behavior is triggered by the following:- Not using a pty to run the subcommand (i.e.
pty=False), as ptys natively echo stdin to stdout on their own; - And when the controlling terminal of Invoke itself (as per
in_stream) appears to be a valid terminal device or TTY. (Specifically, whenisattyyields aTrueresult when givenin_stream.)Note
This property tends to be
Falsewhen piping another program’s output into an Invoke session, or when running Invoke within another program (e.g. running Invoke from itself).
If both of those properties are true, echoing will occur; if either is false, no echoing will be performed.
When not
None, this parameter will override that auto-detection and force, or disable, echoing. - Not using a pty to run the subcommand (i.e.
Returns: Result, or a subclass thereof.Raises: UnexpectedExit, if the command exited nonzero andwarnwasFalse.Raises: Failure, if the command didn’t even exit cleanly, e.g. if aStreamWatcherraisedWatcherError.Raises: ThreadException(if the background I/O threads encountered exceptions other thanWatcherError).
-
generate_result(**kwargs)¶ Create & return a suitable
Resultinstance from the givenkwargs.Subclasses may wish to override this in order to manipulate things or generate a
Resultsubclass (e.g. ones containing additional metadata besides the default).
-
read_proc_output(reader)¶ Iteratively read & decode bytes from a subprocess’ out/err stream.
Parameters: reader – A literal reader function/partial, wrapping the actual stream object in question, which takes a number of bytes to read, and returns that many bytes (or
None).readershould be a reference to eitherread_proc_stdoutorread_proc_stderr, which perform the actual, platform/library specific read calls.Returns: A generator yielding Unicode strings ( unicodeon Python 2;stron Python 3).Specifically, each resulting string is the result of decoding
read_chunk_sizebytes read from the subprocess’ out/err stream.
-
write_our_output(stream, string)¶ Write
stringtostream.Also calls
.flush()onstreamto ensure that real terminal streams don’t buffer.Parameters: - stream – A file-like stream object, mapping to the
out_streamorerr_streamparameters ofrun. - string – A Unicode string object.
Returns: None.- stream – A file-like stream object, mapping to the
-
handle_stdout(buffer_, hide, output)¶ Read process’ stdout, storing into a buffer & printing/parsing.
Intended for use as a thread target. Only terminates when all stdout from the subprocess has been read.
Parameters: Returns: None.
-
handle_stderr(buffer_, hide, output)¶ Read process’ stderr, storing into a buffer & printing/parsing.
Identical to
handle_stdoutexcept for the stream read from; see its docstring for API details.
-
read_our_stdin(input_)¶ Read & decode bytes from a local stdin stream.
Parameters: input – Actual stream object to read from. Maps to in_streaminrun, so will often besys.stdin, but might be any stream-like object.Returns: A Unicode string, the result of decoding the read bytes (this might be the empty string if the pipe has closed/reached EOF); or Noneif stdin wasn’t ready for reading yet.
-
handle_stdin(input_, output, echo)¶ Read local stdin, copying into process’ stdin as necessary.
Intended for use as a thread target.
Note
Because real terminal stdin streams have no well-defined “end”, if such a stream is detected (based on existence of a callable
.fileno()) this method will wait untilprogram_finishedis set, before terminating.When the stream doesn’t appear to be from a terminal, the same semantics as
handle_stdoutare used - the stream is simplyread()from until it returns an empty value.Parameters: - input – Stream (file-like object) from which to read.
- output – Stream (file-like object) to which echoing may occur.
- echo (bool) – User override option for stdin-stdout echoing.
Returns: None.
-
should_echo_stdin(input_, output)¶ Determine whether data read from
input_should echo tooutput.Used by
handle_stdin; tests attributes ofinput_andoutput.Parameters: - input – Input stream (file-like object).
- output – Output stream (file-like object).
Returns: A
bool.
-
respond(buffer_)¶ Write to the program’s stdin in response to patterns in
buffer_.The patterns and responses are driven by the
StreamWatcherinstances from thewatcherskwarg ofrun- see Automatically responding to program output for a conceptual overview.Parameters: buffer (list) – The capture buffer for this thread’s particular IO stream. Returns: None.
-
generate_env(env, replace_env)¶ Return a suitable environment dict based on user input & behavior.
Parameters: - env (dict) – Dict supplying overrides or full env, depending.
- replace_env (bool) – Whether
envupdates, or is used in place of, the value ofos.environ.
Returns: A dictionary of shell environment vars.
-
should_use_pty(pty, fallback)¶ Should execution attempt to use a pseudo-terminal?
Parameters:
-
has_dead_threads¶ Detect whether any IO threads appear to have terminated unexpectedly.
Used during process-completion waiting (in
wait) to ensure we don’t deadlock our child process if our IO processing threads have errored/died.Returns: Trueif any threads appear to have terminated with an exception,Falseotherwise.
-
wait()¶ Block until the running command appears to have exited.
Returns: None.
-
write_proc_stdin(data)¶ Write encoded
datato the running process’ stdin.Parameters: data – A Unicode string. Returns: None.
-
decode(data)¶ Decode some
databytes, returning Unicode.
-
process_is_finished¶ Determine whether our subprocess has terminated.
Note
The implementation of this method should be nonblocking, as it is used within a query/poll loop.
Returns: Trueif the subprocess has finished running,Falseotherwise.
-
start(command, shell, env)¶ Initiate execution of
command(viashell, withenv).Typically this means use of a forked subprocess or requesting start of execution on a remote system.
In most cases, this method will also set subclass-specific member variables used in other methods such as
waitand/orreturncode.
-
read_proc_stdout(num_bytes)¶ Read
num_bytesfrom the running process’ stdout stream.Parameters: num_bytes (int) – Number of bytes to read at maximum. Returns: A string/bytes object.
-
read_proc_stderr(num_bytes)¶ Read
num_bytesfrom the running process’ stderr stream.Parameters: num_bytes (int) – Number of bytes to read at maximum. Returns: A string/bytes object.
-
default_encoding()¶ Return a string naming the expected encoding of subprocess streams.
This return value should be suitable for use by encode/decode methods.
-
send_interrupt(interrupt)¶ Submit an interrupt signal to the running subprocess.
In almost all implementations, the default behavior is what will be desired: submit
to the subprocess’ stdin pipe. However, we leave this as a public method in case this default needs to be augmented or replaced.Parameters: interrupt – The locally-sourced KeyboardInterruptcausing the method call.Returns: None.
-
stop()¶ Perform final cleanup, if necessary.
This method is called within a
finallyclause inside the mainrunmethod. Depending on the subclass, it may be a no-op, or it may do things such as close network connections or open files.Returns: None
-
__weakref__¶ list of weak references to the object (if defined)
-
-
class
invoke.runners.Local(context)¶ Execute a command on the local system in a subprocess.
Note
When Invoke itself is executed without a controlling terminal (e.g. when
sys.stdinlacks a usefulfileno), it’s not possible to present a handle on our PTY to local subprocesses. In such situations,Localwill fallback to behaving as ifpty=False(on the theory that degraded execution is better than none at all) as well as printing a warning to stderr.To disable this behavior, say
fallback=False.
-
class
invoke.runners.Result(stdout='', stderr='', encoding=None, command='', shell='', env=None, exited=0, pty=False, hide=())¶ A container for information about the result of a command execution.
All params are exposed as attributes of the same name and type.
Parameters: - stdout (str) – The subprocess’ standard output.
- stderr (str) – Same as
stdoutbut containing standard error (unless the process was invoked via a pty, in which case it will be empty; seeRunner.run.) - encoding (str) – The string encoding used by the local shell environment.
- command (str) – The command which was executed.
- shell (str) – The shell binary used for execution.
- env (dict) – The shell environment used for execution. (Default is the empty dict,
{}, notNoneas displayed in the signature.) - exited (int) – An integer representing the subprocess’ exit/return code.
- pty (bool) – A boolean describing whether the subprocess was invoked with a pty or
not; see
Runner.run. - hide (tuple) –
A tuple of stream names (none, one or both of
('stdout', 'stderr')) which were hidden from the user when the generating command executed; this is a normalized value derived from thehideparameter ofRunner.run.For example,
run('command', hide='stdout')will yield aResultwhereresult.hide == ('stdout',);hide=Trueorhide='both'results inresult.hide == ('stdout', 'stderr'); andhide=False(the default) generatesresult.hide == ()(the empty tuple.)
Note
Resultobjects’ truth evaluation is equivalent to theirokattribute’s value. Therefore, quick-and-dirty expressions like the following are possible:if run("some shell command"): do_something() else: handle_problem()
However, remember Zen of Python #2.
-
return_code¶ An alias for
.exited.
-
ok¶ A boolean equivalent to
exited == 0.
-
__weakref__¶ list of weak references to the object (if defined)
-
failed¶ The inverse of
ok.I.e.,
Trueif the program exited with a nonzero return code, andFalseotherwise.