what is the use of pexpect.EOF and pexpect.TIMEOUT in python?

Viewed 1044

what is the use of pexpect.EOF and pexpect.TIMEOUT in python.In which scneario it will be usefull ?

1 Answers

The explanation of EOF and TIMEOUT is here, but, in a nutshell:

  1. If Pexpect cannot find one of the search items in expect or expect_exact, it will time out.
  2. If the Pexpect child is closed or was closed during the call, it will return an EOF.

Here is an example:

#!/usr/bin/python3
import pexpect

print("Pexpect TIMEOUT and EOF Test:")
child = pexpect.spawn("python3")
child.expect(">>>")

# Works: You will find the search string (>>>)
child.sendline("print('This is a test.')")
index = child.expect_exact([">>>", pexpect.TIMEOUT, pexpect.EOF, ])
if index == 0:
    print("'>>>' was found, as expected.")

# TIMEOUT: You will not find the search string (Waldo)
child.sendline("print('This is another test.')")
index = child.expect_exact(["Waldo", pexpect.TIMEOUT, pexpect.EOF, ], timeout=5)
if index == 1:
    print("- 'Waldo' could not be found, " +
          "and the search timed out after 5 seconds, as expected.")
child.sendline("exit()")

# EOF: The 'exit()' statement closed the child implicitly (no need for child.close())
# You cannot interact with a closed child, so Pexpect will return an EOF
index = child.expect_exact(["]$", pexpect.TIMEOUT, pexpect.EOF, ])
if index == 2:
    print("Pexpect returned an EOF error on a closed child, as expected.")

# However, you can still get information from the closed child
print("Left in the child: " + str(child.before))

Output:

Pexpect TIMEOUT and EOF Test:
- '>>>' was found, as expected.
- 'Waldo' could not be found, and the search timed out after 5 seconds, as expected.
- Pexpect returned an EOF error on a closed child, as expected.
- Left in the child: b" print('This is another test.')\r\nThis is another test.\r\n>>> exit()\r\n"
Script complete. Have a nice day.

Process finished with exit code 0

Good luck with your code!

Related