找回密码
 立即注册
首页 业界区 业界 PC端自动化测试实战教程-7-pywinauto等待方法大集合 ( ...

PC端自动化测试实战教程-7-pywinauto等待方法大集合 (详细教程)

游瞠离 前天 10:18
1.简介

经过上一篇的学习和讲解想必小伙伴或者童鞋们已经意识到等待的重要性了吧。宏哥在上一篇中在start()后,加入适当的等待时间(如time.sleep()),让应用程序有足够的时间初始化窗口和UI元素。之前我们在做web和app的ui自动化过程中,常用到等待机制,那PC端自动化有这个方法吗?答案是肯定的,python这么强大,肯定是有方法的。今天就跟随宏哥来一起看一下PC端自动化是如何等待的。应用程序行为通常不稳定,您的脚本需要等待,直到出现新窗口或关闭/隐藏现有窗口。 pywinauto可以隐式地(默认超时)灵活地等待对话框初始化,或者明确地使用专用方法/函数来帮助您使代码更容易和更可靠。
2.等待机制

宏哥将其分为三个大类(仅是自己的观点):窗口/元素等待、应用程序等待和全局等待时间Timings。
2.1窗口/元素等待

Pywinauto是一个用于自动化Windows GUI应用程序的模块,提供了两种等待函数:wait()和wait_not()。

  • wait() 等待窗口达到指定状态。
  • wait_not() 等待窗口不处于某种状态。
2.1.1wait()

wait()函数用于等待指定窗口达到指定状态,例如“最大化”或“最小化”状态。你可以通过设置超时时间和重试间隔来控制等待的时间和频率。
1.跟随宏哥先来看一下wait()的源码,然后再进行下一步的学习。wait()的源码如下:
  1.     def wait(self, wait_for, timeout=None, retry_interval=None):
  2.         """
  3.         Wait for the window to be in a particular state/states.
  4.         :param wait_for: The state to wait for the window to be in. It can
  5.             be any of the following states, also you may combine the states by space key.
  6.              * 'exists' means that the window is a valid handle
  7.              * 'visible' means that the window is not hidden
  8.              * 'enabled' means that the window is not disabled
  9.              * 'ready' means that the window is visible and enabled
  10.              * 'active' means that the window is active
  11.         :param timeout: Raise an :func:`pywinauto.timings.TimeoutError` if the window
  12.             is not in the appropriate state after this number of seconds.
  13.             Default: :py:attr:`pywinauto.timings.Timings.window_find_timeout`.
  14.         :param retry_interval: How long to sleep between each retry.
  15.             Default: :py:attr:`pywinauto.timings.Timings.window_find_retry`.
  16.         An example to wait until the dialog
  17.         exists, is ready, enabled and visible: ::
  18.             self.Dlg.wait("exists enabled visible ready")
  19.         .. seealso::
  20.             :func:`WindowSpecification.wait_not()`
  21.             :func:`pywinauto.timings.TimeoutError`
  22.         """
  23.         check_method_names, timeout, retry_interval = self.__parse_wait_args(wait_for, timeout, retry_interval)
  24.         wait_until(timeout, retry_interval,
  25.                    lambda: self.__check_all_conditions(check_method_names, retry_interval))
  26.         # Return the wrapped control
  27.         return self.wrapper_object()
复制代码
2.参数说明:
wait_for 可选参数:

  • ‘exists’ 表示窗口存在,是一个有效的句柄
  • ‘visible’ 表示窗口可见(不隐藏)
  • ‘enabled’ 表示窗口未被禁用
  • ‘ready’ 表示窗口可见且已启用
  • ‘active’ 表示窗口处于活动状态
timeout:表示超时时间
retry_interval:表示重试间隔
2.1.2wait_not()

其实和上面都是一样的,一种等待处于某种状态,一种等待不处于某种状态。wait_not()函数则用于等待指定窗口不处于某种状态,例如“关闭”状态。它的使用方式与wait()函数类似,但参数和返回值有所不同。
1.跟随宏哥先来看一下wait_not()的源码,然后再进行下一步的学习。wait_not()的源码如下:
  1. def wait_not(self, wait_for_not, timeout=None, retry_interval=None):
  2.         """
  3.         Wait for the window to not be in a particular state/states.
  4.         :param wait_for_not: The state to wait for the window to not be in. It can be any
  5.             of the following states, also you may combine the states by space key.
  6.              * 'exists' means that the window is a valid handle
  7.              * 'visible' means that the window is not hidden
  8.              * 'enabled' means that the window is not disabled
  9.              * 'ready' means that the window is visible and enabled
  10.              * 'active' means that the window is active
  11.         :param timeout: Raise an :func:`pywinauto.timings.TimeoutError` if the window is sill in the
  12.             state after this number of seconds.
  13.             Default: :py:attr:`pywinauto.timings.Timings.window_find_timeout`.
  14.         :param retry_interval: How long to sleep between each retry.
  15.             Default: :py:attr:`pywinauto.timings.Timings.window_find_retry`.
  16.         An example to wait until the dialog is not ready, enabled or visible: ::
  17.             self.Dlg.wait_not("enabled visible ready")
  18.         .. seealso::
  19.             :func:`WindowSpecification.wait()`
  20.             :func:`pywinauto.timings.TimeoutError`
  21.         """
  22.         check_method_names, timeout, retry_interval = \
  23.             self.__parse_wait_args(wait_for_not, timeout, retry_interval)
  24.         wait_until(timeout, retry_interval,
  25.                    lambda: not self.__check_all_conditions(check_method_names, retry_interval))
  26.         # None return value, since we are waiting for a `negative` state of the control.
  27.         # Expect that you will have nothing to do with the window closed, disabled, etc.
复制代码
2.参数说明:
wait_not 可选参数:

  • ‘exists’ 表示窗口存在,是一个有效的句柄
  • ‘visible’ 表示窗口可见(不隐藏)
  • ‘enabled’ 表示窗口未被禁用
  • ‘ready’ 表示窗口可见且已启用
  • ‘active’ 表示窗口处于活动状态
timeout:表示超时时间
retry_interval:表示重试间隔
3.应用程序等待

应用程序等待只是针对应用程序的。注意:此方法仅适用于整个应用程序进程,不适用于窗口/元素。
3.1CPU使用率

3.1.1wait_cpu_usage_lower()

wait_cpu_usage_lower(),等待该进程的cup的使用率低于某个阀值。
1.跟随宏哥先来看一下wait_cpu_usage_lower()的源码,然后再进行下一步的学习。wait_cpu_usage_lower()的源码如下:
  1.     def wait_cpu_usage_lower(self, threshold=2.5, timeout=None, usage_interval=None):
  2.         """Wait until process CPU usage percentage is less than the specified threshold"""
  3.         if usage_interval is None:
  4.             usage_interval = Timings.cpu_usage_interval
  5.         if timeout is None:
  6.             timeout = Timings.cpu_usage_wait_timeout
  7.         start_time = timings.timestamp()
  8.         while self.cpu_usage(usage_interval) > threshold:
  9.             if timings.timestamp() - start_time > timeout:
  10.                 raise RuntimeError('Waiting CPU load <= {}% timed out!'.format(threshold))
  11.         return self
复制代码
5.4运行代码

1.运行代码,右键Run'Test',就可以看到控制台输出,如下图所示:
1.png

2.运行代码后电脑端的动作(启动记事本)。如下图所示:
2.gif

6.小结

6.1.基础窗口状态等待方法‌

wait() 方法‌
支持等待窗口达到特定状态,包括:
'exists':窗口句柄有效
'visible':窗口未隐藏
'enabled':窗口未被禁用
'ready':窗口可见且已启用
'active':窗口处于活动状态
参数说明:
timeout:超时时间(默认由全局配置决定)
retry_interval:重试间隔(默认由全局配置决定)‌
6.2.高级场景等待方法‌

wait_cpu_usage_lower()‌
适用于多线程应用中延迟初始化的场景,通过监控进程的CPU使用率判断任务是否完成(如后台计算未结束前保持等待)‌
wait_until_passes()‌
持续执行指定操作直至成功或超时,特别适用于动态加载的控件或异步操作后的状态检测‌
6.3 ‌全局等待时间配置

通过 timings 模块设置默认超时和轮询间隔:
Timings.Defaults.timeout:全局超时时间(默认30秒)
Timings.Defaults.retry_interval:全局重试间隔(默认0.5秒)
6.4. ‌使用建议‌

优先使用内置等待机制‌(如 wait() 和 wait_until_passes()),避免依赖 time.sleep(),以提高代码稳定性和执行效率‌
对于复杂界面,结合 print_control_identifiers() 输出控件信息以辅助定位目标元素‌
注:以上方法需根据具体场景选择,合理设置超时参数可避免因界面响应延迟导致的自动化失败。
好了,关于pywinauto等待方法大集合常用的也就那几个非常简单,时间不早了今天就分享到这里,感谢你耐心地阅读!
                                                公众号(关注宏哥)&NonBreakingSpace; &NonBreakingSpace;&NonBreakingSpace;&NonBreakingSpace;                        &NonBreakingSpace; &NonBreakingSpace; &NonBreakingSpace;&NonBreakingSpace;&NonBreakingSpace;&NonBreakingSpace;                        &NonBreakingSpace;&NonBreakingSpace;&NonBreakingSpace; &NonBreakingSpace;&NonBreakingSpace;&NonBreakingSpace;                        &NonBreakingSpace;&NonBreakingSpace;&NonBreakingSpace; &NonBreakingSpace;&NonBreakingSpace;&NonBreakingSpace;                        微信群(扫码进群) &NonBreakingSpace;&NonBreakingSpace;&NonBreakingSpace;                        &NonBreakingSpace;&NonBreakingSpace;&NonBreakingSpace; &NonBreakingSpace;&NonBreakingSpace;&NonBreakingSpace;                        &NonBreakingSpace;&NonBreakingSpace;&NonBreakingSpace; &NonBreakingSpace;&NonBreakingSpace;&NonBreakingSpace;                        &NonBreakingSpace;&NonBreakingSpace;&NonBreakingSpace;&NonBreakingSpace;                        &NonBreakingSpace;&NonBreakingSpace;&NonBreakingSpace; &NonBreakingSpace;&NonBreakingSpace;                        &NonBreakingSpace;&NonBreakingSpace;&NonBreakingSpace; &NonBreakingSpace;&NonBreakingSpace;客服微信               
               
3.png
               
4.png
               
5.png

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册