// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Uses an interactive Python as a calculator: waits for its prompt, sends it //! an expression, and reads back the answer or the exception it raised. //! //! zig build example -- '6 * 7' '2 ** 100' '1 / 0' const std = @import("std"); const expect = @import("expect"); const Regex = expect.zregex.Regex; const Reply = enum { answer, exception }; pub fn main(init: std.process.Init) !void { const io = init.io; const gpa = init.gpa; var stdout_buffer: [1024]u8 = undefined; var stdout_writer = std.Io.File.stdout().writer(io, &stdout_buffer); const out = &stdout_writer.interface; // Python's own line editor echoes what it is sent even with the // terminal's echo off, so each reply is the expression, then the answer, // then the next prompt. The patterns anchor on that prompt, so that only // a complete reply matches. var prompt = try Regex.compile(gpa, ">>> $"); defer prompt.deinit(); var answer = try Regex.compile(gpa, "(?m)^([^\\r\\n]*)\\r?\\n>>> $"); defer answer.deinit(); var exception = try Regex.compile(gpa, "(?m)^(\\w+(?:Error|Exception)[^\\r\\n]*)\\r?\\n>>> $"); defer exception.deinit(); // Python 3.13 and later draw a coloured prompt with escape sequences // around it; ask for the plain one, which is easier to match. var env = try init.environ_map.clone(gpa); defer env.deinit(); try env.put("PYTHON_BASIC_REPL", "1"); try env.put("NO_COLOR", "1"); try env.put("TERM", "dumb"); var buffer: [8192]u8 = undefined; var session = try expect.Session.spawn(io, gpa, &buffer, .{ .argv = &.{ "python3", "-q", "-i" }, .environ_map = &env, }); defer session.deinit(); { var ready = try session.expect(void, &.{.{ .tag = {}, .regex = &prompt }}, expect.within(.fromSeconds(10))); ready.deinit(gpa); } const args = try init.minimal.args.toSlice(init.arena.allocator()); for (args[1..]) |expression| { try session.sendLine(expression); var reply = session.expect(Reply, &.{ // Tried first: a traceback's last line would match `answer` too. .{ .tag = .exception, .regex = &exception }, .{ .tag = .answer, .regex = &answer }, }, expect.within(.fromSeconds(10))) catch |err| switch (err) { error.Timeout => { try out.print("{s}: no answer in time\n", .{expression}); break; }, error.EndOfStream => { try out.print("{s}: python exited\n", .{expression}); break; }, else => |e| return e, }; defer reply.deinit(gpa); switch (reply.tag) { .answer => try out.print("{s} = {s}\n", .{ expression, reply.group(1).? }), .exception => try out.print("{s} raised {s}\n", .{ expression, reply.group(1).? }), } } try session.sendEof(); if (session.expect(void, &.{}, expect.within(.fromSeconds(10)))) |r| { var result = r; result.deinit(gpa); } else |err| switch (err) { error.EndOfStream => {}, else => |e| return e, } const term = try session.wait(); try out.print("python exited: {any}\n", .{term}); try out.flush(); }