File: expectex.lua

package info (click to toggle)
lua-lpty 1.0.1-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 168 kB
  • sloc: ansic: 546; makefile: 34
file content (73 lines) | stat: -rw-r--r-- 1,700 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/env lua

--[[ expectbc.lua
 -
 - a somewhat less simple example for lpty, using bc via quite simplistic
 - expect like functionality
 -
 - Gunnar Zötl <gz@tset.de>, 2010, 2011
 - Released under MIT/X11 license. See file LICENSE for details.
--]]

local lpty = require "lpty"

local function start(...)
	local p = lpty.new()
	p:startproc(...)
	while p:hasproc() and not p:readok() do end
	if not p:hasproc() then
		local what, code = p:exitstatus()
		error("start failed: child process terminated because of " .. tostring(what) .. " " ..tostring(code))
	end
	return p
end

local function expect(p, what, plain, timeout)
	if not p:hasproc() then return nil, "no running process." end
	local res = ""
	local found = false

	-- consume all output from client while searching for our pattern
	while not found do
		local r, why = p:read(timeout)
		if r ~= nil then
			res = res .. r
			local first, last, capture = string.find(res, what, 1, plain)
			if first then
				if capture then
					found = capture
				else
					found = string.sub(res, first, last)
				end
			end
		else
			if why then
				error("read failed: " .. why)
			else
				local what, code = p:exitstatus()
				if what then
					error("read failed: child process terminated because of " .. tostring(what) .. " " ..tostring(code))
				end
			end
		end
	end
	return found
end

local function send(p, what)
	local s = p:send(what)
	-- wait for reply
	while not p:readok() and p:hasproc() do end
	return s
end

-- and here's how we use it
p = start("lua")
if expect(p, "> $") then
	send(p, "=111+234\n")
	res = expect(p, "([0-9]+)[^0-9]*> $")
	print("Got '"..tostring(res).."'")
	send(p, "os.exit()\n")
else
	print "Whoops..."
end