繁体   English   中英

python中pexpect.EOF和pexpect.TIMEOUT有什么用?

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

pexpect.EOF 和 pexpect.TIMEOUT 在 python 中的用途是什么。在哪个场景中它会很有用?

EOF 和 TIMEOUT 的解释在这里,但是,简而言之:

  1. 如果 Pexpect 在expectexpect_exact找不到搜索项之一,它将超时。
  2. 如果 Pexpect 子进程关闭或在调用过程中被关闭,它将返回一个 EOF。

下面是一个例子:

#!/usr/bin/python3
import pexpect

print("Pexpect TIMEOUT and EOF Test:")
child = pexpect.spawn("/usr/bin/env python")
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

祝你的代码好运!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM