zig-expect #
A Zig 0.16 library for driving interactive programs, in the manner of Tcl's
expect: start a program, wait for one of several regular expressions to turn
up in what it prints, learn which one did and what it captured, and send it
input in reply.
API documentation, generated from the doc comments, is at
https://jeff.jcollie.page/zig-expect/. Build it locally with
zig build docs, and read it with zig build docs-serve.
Regular expressions are zregex's.
Usage #
const std = @import("std");
const expect = @import("expect");
const Regex = expect.zregex.Regex;
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var password = try Regex.compile(gpa, "[Pp]assword: $");
defer password.deinit();
var shell = try Regex.compile(gpa, "(\\w+)@\\S+ ?[$#] $");
defer shell.deinit();
// Output is held here until it is matched. The library never allocates
// for it, so this is also the most unmatched output there can be.
var buffer: [4096]u8 = undefined;
var session = try expect.Session.spawn(init.io, gpa, &buffer, .{
.argv = &.{ "ssh", "host.example.org" },
.environ_map = init.environ_map,
});
defer session.deinit();
const Prompt = enum { password, shell };
var result = try session.expect(Prompt, &.{
.{ .tag = .password, .regex = &password },
.{ .tag = .shell, .regex = &shell },
}, expect.within(.fromSeconds(10)));
defer result.deinit(gpa);
switch (result.tag) {
.password => try session.sendLine("hunter2"),
.shell => std.debug.print("logged in as {s}\n", .{result.group(1).?}),
}
}
examples/python.zig is a complete program, which drives an interactive
Python as a calculator:
$ zig build example -- '6 * 7' '2 ** 100' '1 / 0'
6 * 7 = 42
2 ** 100 = 1267650600228229401496703205376
1 / 0 raised ZeroDivisionError: division by zero
python exited: .{ .exited = 0 }
To depend on it:
zig fetch --save git+https://git.jcollie.dev/jeff/zig-expect
const expect = b.dependency("expect", .{ .target = target, .optimize = optimize });
exe.root_module.addImport("expect", expect.module("expect"));
How expect matches #
- The first pattern in the list wins. Each time output arrives, every
pattern is tried, in the order given, against everything not yet consumed.
The first one that matches is the answer, even if a later one matches
earlier in the output. This is Tcl
expect's rule. - A match consumes the output up to its end. The result's
textis everything from the end of the previous match to the end of this one, and every span inresult.matchis an index into it.before()is the part ahead of the match, andgroup(i)is a capture group as text. - What follows a match is kept. Output that arrived in the same read and
goes past the match waits for the next
expect, which searches it before reading anything. - The timeout covers the whole call. A child that keeps printing things
nobody is waiting for does not extend it.
expect.within(duration)makes one; anystd.Io.Timeoutworks, and.nonewaits indefinitely. - The result points into the buffer.
textstays valid until the next call that reads or discards. The capture groups are allocated, and freed withresult.deinit(gpa).
expect returns an error if no pattern matches:
| Error | Meaning |
|---|---|
error.Timeout |
The deadline passed. |
error.EndOfStream |
The child closed its output, usually by exiting. wait() gives its exit status. |
error.BufferFull |
The buffer is full of output that no pattern matches. pending() shows it and discard(n) makes room. |
A full buffer is the one place this differs from Tcl expect, which quietly
forgets the oldest output. Here it is reported instead, so that the output
the caller is waiting for is never cut in half.
Talking back #
| Call | Does |
|---|---|
send(bytes) |
Writes the bytes as given. |
sendLine(line) |
Writes the line, then a carriage return on a terminal (what the Enter key sends) or a newline on a pipe. |
sendEof() |
On a terminal, sends the end-of-file character (normally ^D), which ends input at the start of a line. On a pipe, closes standard input. |
sendSignal(sig) |
Signals the child. POSIX only. |
setWindowSize(size) |
Resizes the terminal, which sends the child SIGWINCH. |
wait() |
Waits for the child to exit and returns its std.process.Child.Term. |
kill() |
Kills the child with SIGKILL and collects it. |
kill uses SIGKILL rather than the SIGTERM used by
std.process.Child.kill, because an interactive shell ignores SIGTERM, so
waiting for it to exit would never return. deinit kills a child that is
still running.
Transports #
Options.transport chooses how the child is connected.
.pty, the default on POSIX systems, runs the child on a pseudo-terminal
that becomes its controlling terminal. Programs behave as they would for a
person: output is line-buffered instead of held back in blocks, and prompts
that read /dev/tty, such as ssh, sudo and passwd, work. Standard
output and standard error arrive together, in the order they were written.
The terminal's echo is off by default (Options.echo), so what is sent does
not come back to be matched.
std.process.spawn cannot set this up. The child must call setsid and
then claim the terminal with TIOCSCTTY between fork and execve, and the
standard library has no way to run code at that point. So src/pty.zig
forks and execs by itself, following std.Io.Threaded's approach: everything
is allocated before the fork, and a close-on-exec pipe carries any failure
back to the parent. On Linux it makes raw system calls and needs no libc.
Other POSIX systems go through libc.
.pipe uses plain pipes through std.process.spawn, and is the default
on Windows. It works everywhere, but many programs buffer their output when
it is not going to a terminal. Standard error is read along with standard
output unless Options.merge_stderr is false. On a pipe, call wait after
error.EndOfStream, not before: std.process.Child.wait closes the pipes.
Either way, output is read straight into the caller's buffer. Both pipes read at once, each into half of the free space, and the second's bytes are then moved down to follow the first's.
The environment #
Zig 0.16 hands the environment to main rather than keeping it in a global,
so Options.environ_map is required: pass init.environ_map to inherit it,
or a modified copy. argv[0] is looked up in that map's PATH when it
contains no slash.
Platforms #
| Platform | .pty |
.pipe |
Tested |
|---|---|---|---|
| Linux, no libc | yes | yes | yes |
| Linux, with libc | yes | yes | yes |
| macOS, the BSDs | yes | yes | compiles only |
| Windows | no | yes | compiles only |
The two Linux rows are separate code paths. Without libc, the terminal is
opened through /dev/ptmx with raw ioctls. With libc, it goes through
posix_openpt, grantpt, unlockpt and ptsname, which is what macOS and
the BSDs run. Linking libc on Linux is how that second path gets tested:
zig build test -Dlink-libc -Dtarget=native-linux-musl
Building #
nix develop # Zig 0.16, reuse, zon2nix, git-pages-cli
zig build test # the tests: each one runs a real /bin/sh
zig build check -Dtarget=... # compile everything for another system
zig build example -- '6 * 7' # the Python calculator
zig build docs # API documentation into zig-out/docs
nix build # the package, with the tests run in the sandbox
build.zig.zon.nix is generated from build.zig.zon. Regenerate it after
changing a dependency:
nix develop -c zon2nix --16 --nix=build.zig.zon.nix build.zig.zon
Source #
The repository lives at https://git.jcollie.dev/jeff/zig-expect:
git clone https://git.jcollie.dev/jeff/zig-expect.git
It is mirrored on Tangled at https://tangled.org/jcollie.dev/zig-expect,
and on Radicle as rad:z2WMCGpZ3tsPvhCqwHJosyCsp94jo:
rad clone rad:z2WMCGpZ3tsPvhCqwHJosyCsp94jo
License #
MIT. The project follows the REUSE specification,
and reuse lint checks it.
References cited #
- Libes, Don. expect(1) — programmed dialogue with interactive programs. Linux man page. https://linux.die.net/man/1/expect. Accessed 2026-09-29.
- The Linux man-pages project. pty(7) — pseudoterminal interfaces. Linux manual pages. https://man7.org/linux/man-pages/man7/pty.7.html. Accessed 2026-09-29.
- The Linux man-pages project. posix_openpt(3) — open a pseudoterminal device. Linux manual pages. https://man7.org/linux/man-pages/man3/posix_openpt.3.html. Accessed 2026-09-29.
- The Linux man-pages project. TIOCSCTTY(2const) — make the given terminal the controlling terminal. Linux manual pages. https://man7.org/linux/man-pages/man2/TIOCSCTTY.2const.html. Accessed 2026-09-29.