|
// retoor <retoor@molodetz.nl>
|
|
|
|
import "pexpect" for Spawn, Pexpect
|
|
|
|
System.print("=== Pexpect Module Demo ===\n")
|
|
|
|
System.print("--- Basic Spawn and Expect ---")
|
|
var child = Spawn.new("echo 'Hello from pexpect!'")
|
|
var idx = child.expect(["Hello"])
|
|
System.print("Matched pattern index: %(idx)")
|
|
System.print("After match: %(child.after)")
|
|
child.close()
|
|
|
|
System.print("\n--- Interactive Process ---")
|
|
child = Spawn.new("cat")
|
|
child.sendline("First line")
|
|
child.expect(["First line"])
|
|
System.print("Echo received: %(child.after)")
|
|
child.sendline("Second line")
|
|
child.expect(["Second line"])
|
|
System.print("Echo received: %(child.after)")
|
|
child.sendeof()
|
|
child.close()
|
|
|
|
System.print("\n--- Multiple Patterns ---")
|
|
child = Spawn.new("printf 'username: '")
|
|
idx = child.expect(["password:", "username:", "login:"])
|
|
System.print("Matched: %(idx == 1 ? "username" : "other")")
|
|
child.close()
|
|
|
|
System.print("\n--- Exact String Matching ---")
|
|
child = Spawn.new("echo 'The answer is 42'")
|
|
idx = child.expectExact(["42"])
|
|
System.print("Found exact match: %(child.after)")
|
|
System.print("Text before: %(child.before)")
|
|
child.close()
|
|
|
|
System.print("\n--- Timeout Handling ---")
|
|
child = Spawn.new("sleep 10")
|
|
child.timeout = 0.5
|
|
idx = child.expect(["never_match"])
|
|
if (idx == Pexpect.TIMEOUT) {
|
|
System.print("Got timeout as expected")
|
|
}
|
|
child.terminate(true)
|
|
child.close()
|
|
|
|
System.print("\n--- Process Properties ---")
|
|
child = Spawn.new("echo test")
|
|
System.print("PID: %(child.pid)")
|
|
System.print("Is alive: %(child.isalive)")
|
|
child.expect(["test"])
|
|
child.wait()
|
|
System.print("Exit status: %(child.exitstatus)")
|
|
child.close()
|
|
|
|
System.print("\n--- Read Non-blocking ---")
|
|
child = Spawn.new("printf 'quick output'")
|
|
var data = child.readNonblocking(100, 1)
|
|
System.print("Read: %(data.trim())")
|
|
child.close()
|
|
|
|
System.print("\n--- Constants ---")
|
|
System.print("EOF constant: %(Pexpect.EOF)")
|
|
System.print("TIMEOUT constant: %(Pexpect.TIMEOUT)")
|
|
|
|
System.print("\n--- Pexpect.run() ---")
|
|
var output = Pexpect.run("echo 'Simple run'")
|
|
System.print("Output: %(output.trim())")
|
|
|
|
System.print("\n=== Demo Complete ===")
|