跳到内容

发送按键

在这个示例中,favoritecolor.py 是我们试图交互的程序。 它提示两次 - 询问最喜欢的颜色和最喜欢的电影,并将答案写入两个不同的文件。

与之交互需要等待消息出现,模拟打字,再次等待并再次打字。

favoritecolor.py

import sys
import time

answer = input("favorite color:")

with open("color.txt", "w") as handle:
    handle.write(answer)

answer = input("favorite movie:")

with open("movie.txt", "w") as handle:
    handle.write(answer)

time.sleep(0.2)
sys.exit(0)

带代码

from icommandlib import ICommand
from commandlib import python
import time

process = ICommand(python("favoritecolor.py")).run()
process.wait_until_output_contains("favorite color:")
process.send_keys("red\n")
process.wait_until_output_contains("favorite movie:")
process.send_keys("the usual suspects\n")
process.wait_until_on_screen("favorite color")

成功

process.wait_for_successful_exit()
  • 当代码运行到完成时。

然后,color.txt 的文件内容将是

red

然后,movie.txt 的文件内容将是

the usual suspects

已退出

process.wait_for_successful_exit()

# We should have already known that the process would be finished
process.send_keys("oops")

将引发类型为 icommandlib.exceptions.AlreadyExited 的异常,消息为

Process already exited with 0. Output:
favorite color:red
favorite movie:the usual suspects

意外退出后

time.sleep(0.5)

# We didn't necessarily know that the process finished but it did
process.send_keys("oops")

将引发类型为 icommandlib.exceptions.UnexpectedExit 的异常,消息为

Process unexpectedly exited with exit code 0. Output:
favorite color:red
favorite movie:the usual suspects

可执行规范

send-keys.story storytests 自动生成的文档。