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

标签 python pexpect

pexpect.EOF 和 pexpect.TIMEOUT 在 python 中有何用途。在哪些场景中它会很有用?

最佳答案

EOF和TIMEOUT的解释是here ,但是,简而言之:

  1. 如果 Pexpect 在 expectexpect_exact 中找不到搜索项之一,则会超时。
  2. 如果 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/

相关文章:

python - 用于在远程服务器上运行命令的交互式 Python 脚本

python - 在 pexpect 交互方面需要很少的帮助

python - 预期的文件写入命令不会像我想象的那样表现

python - 查找对数表示的矩阵的特征值

Python通配符匹配

python - urllib2 给出 HTTP 错误 400 : Bad Request for certain urls, 对其他人有效

python - 无法使用 cygwin 运行 pexect

python - pygame 中的记分板没有将玩家按顺序排列,甚至没有显示他们

python - Odoo 8,获取错误 'datestyle' 设置

python - 在 pexpect.run() 中包含通配符