knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.path = "man/figures/README-", out.width = "100%" )

rexpect is an R package that allows you to automate interactions with programs that
expose a text terminal interface. The API is inspired by the original Expect tool by Don Libes.
You can install the development version from GitHub with:
# install.packages("remotes") remotes::install_github("jeroenjanssens/rexpect")
Let's say we have a Python script that repeatedly asks for a number.
When the user enters sum, the script prints the sum of all the numbers.
The script exits when the user presses CTRL-C.
Here's the contents of bin/sum.py:
```{verbatim, file = "bin/sum.py", lang = "python"}
We can use `rexpect` to run this script and interact with it. Let's enter the numbers 7, 13, and 22 and see what the sum is: ```r library(rexpect) session <- spawn("bin/sum.py", prompt = "^(.*):$") send_lines(session, c("7", "13", "22", "sum"), wait = TRUE)
Under the hood, rexpect starts a tmux session using tmuxr:
session
We can capture the output and extract the sum:
print(output <- read_all(session)) as.numeric(gsub("[^0-9.]", "", output[length(output) - 1]))
We've accomplished our goal, so let's exit:
send_lines(session, "exit") read_all(session)
Oh that's right, we need to press CTRL-C to exit the script:
send_control_c(session)
This was a rather simple example to demonstrate some of the capabilities of rexpect.
The session could have taken place inside a Docker container or over SSH.
We could also have recorded the session using asciinema.
Have a look at the function reference to learn more about what rexpect has to offer.
The rexpect package is licensed under the MIT License.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.