Debian Codegraph @

sites/docs/concepts/watchers.rst

raw
1 .. _autoresponding:
2
3 ==========================================
4 Automatically responding to program output
5 ==========================================
6
7 Background
8 ==========
9
10 Command-line programs tend to be designed for interactive shells, which
11 frequently manifests as waiting around for user input, or "prompts".
12 Well-designed programs offer options for pre-empting such prompts, resulting in
13 an easily automated workflow -- but with the rest, interactivity is
14 unavoidable.
15
16 Thankfully, Invoke's `.Runner` class not only forwards your standard input to
17 the running program (allowing you to manually respond to prompts) but it can
18 also be configured to respond automatically on your behalf.
19
20 Basic use
21 =========
22
23 The mechanism for this automation is the ``watchers`` kwarg to the
24 `.Runner.run` method (and its wrappers elsewhere, such as `.Context.run` and
25 `invoke.run`), which is a list of `.StreamWatcher`-subclass instances
26 configured to watch for patterns & respond accordingly. The simplest of these
27 is `.Responder`, which just replies with its configured response every time its
28 pattern is seen; others can be found in the :doc:`watchers module
29 </api/watchers>`.
30
31 .. note::
32 As with all other arguments to ``run``, you can also set the default set of
33 watchers globally via :doc:`configuration files <configuration>`.
34
35 Take for example this program which expects a manual response to a yes/no
36 prompt::
37
38 $ excitable-program
39 When you give the OK, I'm going to do the things. All of them!!
40 Are you ready? [Y/n] y
41 OK! I just did all sorts of neat stuff. You're welcome! Bye!
42
43 You *could* call ``run("excitable-program")``, manually watch for the
44 prompt, and mash Y by hand. But if you instead supply a `.Responder` like so::
45
46 @task
47 def always_ready(c):
48 responder = Responder(
49 pattern=r"Are you ready? \[Y/n\] ",
50 response="y\n",
51 )
52 c.run("excitable-program", watchers=[responder])
53
54 Then `.Runner` passes the program's ``stdout`` and ``stderr`` through
55 ``responder``, which watches for ``"Are you ready? [Y/n] "`` and automatically
56 writes ``y`` (plus ``\n`` to simulate hitting Enter/Return) to the program's
57 ``stdin``.
58
59 .. note::
60 The pattern argument to `.Responder` is treated as a `regular expression
61 <re>`, requiring more care (note how we had to escape our square-brackets
62 in the above example) but providing more power as well.