pexpect.EOF 和 pexpect.TIMEOUT 在 python 中有何用途。在哪些场景中它会很有用?
最佳答案
EOF和TIMEOUT的解释是here ,但是,简而言之:
- 如果 Pexpect 在
expect
或expect_exact
中找不到搜索项之一,则会超时。 - 如果 Pexpect 子级已关闭或在调用期间关闭,它将返回 EOF。
这是一个例子:
#!/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))
输出:
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
祝你的代码好运!
关于python - python 中 pexpect.EOF 和 pexpect.TIMEOUT 有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69535633/