Skip to content

Commit

Permalink
Add an example for interact session with callbacks
Browse files Browse the repository at this point in the history
Co-authored-by: Gary Boone <https://github.com/GaryBoone/>
Signed-off-by: Maxim Zhiburt <[email protected]>
  • Loading branch information
zhiburt committed Sep 27, 2021
1 parent d4cc01c commit ba9652b
Show file tree
Hide file tree
Showing 4 changed files with 104 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,7 @@ Cargo.lock

# These are backup files generated by rustfmt
**/*.rs.bk

# Python cache
**/*.pyc
__pycache__
31 changes: 31 additions & 0 deletions examples/interact_with_callbacks.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#[cfg(not(feature = "async"))]
fn main() {
let mut session =
expectrl::spawn("python ./tests/source/ansi.py").expect("Can't spawn a session");

let opts = expectrl::interact::InteractOptions::terminal()
.unwrap()
.on_input("HelloWorld!", |_| {
print!("You typed a magic word...\r\n");
Ok(())
});

opts.interact(&mut session).unwrap();
}

#[cfg(feature = "async")]
fn main() {
let mut session =
expectrl::spawn("python ./tests/source/ansi.py").expect("Can't spawn a session");

let opts = expectrl::interact::InteractOptions::terminal()
.unwrap()
.on_input("HelloWorld!", |session| {
print!("You typed a magic word...\r\n");
Ok(())
});

futures_lite::future::block_on(async {
opts.interact(&mut session).await.unwrap();
});
}
54 changes: 54 additions & 0 deletions tests/source/ansi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
#!/usr/bin/env python3

# The file was developed by https://github.com/GaryBoone/

from colors import colorize, Color
import sys
import time
import getpass

NUM_LINES = 5
SAME_LINE_ESC = "\033[F"

def main():
"""Demonstrate several kinds of terminal outputs.
Examples including ANSI codes, "\r" without "\n", writing to stdin, no-echo
inputs.
"""

# Show a color.
print("status: ", colorize("good", Color.GREEN))

# Show same-line output via "\r".
for i in range(NUM_LINES):
sys.stdout.write(f"[{i+1}/{NUM_LINES}]: file{i}\r")
time.sleep(1)
print("\n")

# Show same-line output via an ANSI code.
for i in range(NUM_LINES):
print(f"{SAME_LINE_ESC}[{i+1}/{NUM_LINES}]: file{i}")
time.sleep(1)

# Handle prompts which don't repeat input to stdout.
print("Here is a test password prompt")
print(colorize("Do not enter a real password", Color.RED))
getpass.getpass()

# Handle simple input.
ans = input("Continue [y/n]:")
col = Color.GREEN if ans == "y" else Color.RED
print(f"You said: {colorize(ans, col)}")
if ans == "n" or ans == "":
sys.exit(0)

# Handle long-running process, like starting a server.
print("[Starting long running process...]")
print("[Ctrl-C to exit]")
while True:
print("status: ", colorize("good", Color.GREEN))
time.sleep(1)

if __name__ == "__main__":
main()
15 changes: 15 additions & 0 deletions tests/source/colors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import enum

class Color(enum.Enum):
RESET = "\33[0m"
RED = "\33[31m"
GREEN = "\33[32m"
YELLOW = "\33[33m"


def colorize(text: str, color: Color) -> str:
"""Wrap `text` in terminal color directives.
The return value will show up as the given color when printed in a terminal.
"""
return f"{color.value}{text}{Color.RESET.value}"

0 comments on commit ba9652b

Please sign in to comment.