【问题标题】:Cannot handle PYWINAUTO related exceptions with `try except` block in Python properly?无法在 Python 中使用“try except”块正确处理与 PYWINAUTO 相关的异常?
【发布时间】:2021-10-18 09:18:53
【问题描述】:

我的主要目标:自动化Zoom

我的 zoomModule.py 文件是:

import os, pywinauto
from pywinauto import Desktop
from pywinauto import findwindows
from pywinauto.application import Application
from pywinauto.keyboard import send_keys

# Create a instance of Application()
app = Application(backend="uia")


def get_Zoom_Main_Window():
    """starts and connect to zoom main window"""
    zoom_exe_path = os.path.join(
        os.environ["USERPROFILE"], "AppData", "Roaming", "Zoom", "bin", "Zoom.exe"
    )
    try:
        print("starts and connect to zoom main window")
        start = app.start(
            zoom_exe_path,
            timeout=100,
        )
        print("1. Zoom Started")
        connected = start.connect(title="Zoom", timeout=5)
        print("1. Zoom Connected")
        return connected
    except (
        pywinauto.findwindows.ElementNotFoundError,
        pywinauto.timings.TimeoutError,
    ) as e:
        print("Err_context before 2nd try: ", e.__context__)
        try:
            print("Second try")
            start = app.start(
                zoom_exe_path,
                timeout=100,
            )
            print("2. Zoom started")
            connected = start.connect(title="Zoom - Not connected", timeout=20)
            print("2. Zoom connected")
            return connected
        except (
            pywinauto.findwindows.ElementNotFoundError,
            pywinauto.timings.TimeoutError,
        ) as err:
            print(err.__context__)
            print("Unknown Problem; Check internet connection and try again!")


def open_join_meeting_window():
    """opens the Join Meeting Popup Window; returns the Join Meeting Window"""
    zoomMainWin = get_Zoom_Main_Window()
    zoomMainWin["Zoom"].child_window(
        title="Home", control_type="TabItem"
    ).wrapper_object().click_input()
    zoomMainWin["Zoom"].child_window(
        title="Join", control_type="Button"
    ).wrapper_object().click_input()
    try:
        joinMeetingWin = app.connect(title="Join Meeting", timeout=15)
        print("Connected to Join Meeting Window.")
    except (findwindows.ElementNotFoundError, pywinauto.timings.TimeoutError) as e:
        print("Err before joinMeetingWin: ", e)
        pass
        # joinMeetingWin['Join Meeting']


hek = open_join_meeting_window()
print("Haa! out of the function")

终端,当我运行上述文件时:

PS D:\PythonDevelopment\my_CLI_tools> python zoomModule.py
starts and connect to zoom main window
1. Zoom Started
1. Zoom Connected
Err before joinMeetingWin:  
Haa! out of the function
PS D:\PythonDevelopment\my_CLI_tools>

查看eopen_join_meeting_window() 中的Err before joinMeetingWin: 之后如何不打印或保持空白。
get_Zoom_Main_Window() 中的 try-except 块也会发生同样的情况

我曾在谷歌上寻求帮助,但无济于事。

我想达到什么目的?

最低期望:我可以print() pywinauto 向控制台/终端提出的错误而不会导致我的代码崩溃。
更多期望:我可以避免@如果可能的话,在我的代码中使用 987654330@ 块。实现finding and connecting to the required windowgetting hold of child_window()switching between open windows 的更好方法。

我的方法可能是错误的。在这种情况下,请告诉我正确的程序。

【问题讨论】:

  • @abdou_dev 你能帮我解决这个问题吗?请问??
  • 请人帮忙!!!
  • @VasilyRyabov 你能帮帮我吗!我真的被困住了。

标签: python pywinauto


【解决方案1】:

在这个answer的帮助下,我似乎已经知道如何print() the errors raised by pywinauto to the console/terminal without crashing my code了。

open_join_meeting_window 函数 - 之前 ↓↓↓

# after imports
def open_join_meeting_window():
    """opens the Join Meeting Popup Window; returns the Join Meeting Window"""
    zoomMainWin = get_Zoom_Main_Window()
    zoomMainWin["Zoom"].child_window(
        title="Home", control_type="TabItem"
    ).wrapper_object().click_input()
    zoomMainWin["Zoom"].child_window(
        title="Join", control_type="Button"
    ).wrapper_object().click_input()
    try:
        joinMeetingWin = app.connect(title="Join Meeting", timeout=15)
        print("Connected to Join Meeting Window.")
    except (findwindows.ElementNotFoundError, pywinauto.timings.TimeoutError) as e:
        print("Err before joinMeetingWin: ", e)
        pass

open_join_meeting_window函数-修改后 ↓↓↓

def open_join_meeting_window():
    """opens the Join Meeting Popup Window; returns the Join Meeting Window"""
    zoomMainWin = get_Zoom_Main_Window()
    zoomMainWin["Zoom"].child_window(
        title="Home", control_type="TabItem"
    ).wrapper_object().click_input()
    zoomMainWin["Zoom"].child_window(
        title="Join", control_type="Button"
    ).wrapper_object().click_input()
    try:
        joinMeetingWin = app.connect(title="Join Meeting", timeout=15)
        print("Connected to Join Meeting Window.")
    except Exception as e:
        logging.error(traceback.format_exc())
        if e.__class__.__name__ == "TimeoutError":
            print("[TimeoutError]:- The `Join Meeting Window` is taking longer time to appear.")
    print("Passed the try-except block!!")
        pass

新终端日志↓↓↓

ERROR:root:Traceback (most recent call last):
  File "C:\Users\RAKTIM BHATTACHARYA.000\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\timings.py", line 436, in wait_until_passes
    func_val = func(*args, **kwargs)
  File "C:\Users\RAKTIM BHATTACHARYA.000\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\findwindows.py", line 87, in find_element  
    raise ElementNotFoundError(kwargs)
pywinauto.findwindows.ElementNotFoundError: {'title': 'hhh', 'backend': 'uia', 'visible_only': False}

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\PythonDevelopment\Lake\zoom\getJoinMeetingWindow.py", line 14, in open_join_meeting_window
    joinMeetingWin = app.connect(title="hhh", timeout=6)
  File "C:\Users\RAKTIM BHATTACHARYA.000\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\application.py", line 990, in connect      
    self.process = timings.wait_until_passes(
  File "C:\Users\RAKTIM BHATTACHARYA.000\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\timings.py", line 458, in wait_until_passes
    raise err
pywinauto.timings.TimeoutError

[TimeoutError]:- The `Join Meeting Window` is taking longer time to appear.
Passed the try-except block!!

首先,打印传统的回溯。然后在控制流中使用pywinauto 引发的错误名称来决定要做什么。

【讨论】:

  • 你到底有什么问题?你想打印异常还是解决异常?
  • @abdou_dev 解决异常并打印它们而不会使程序崩溃。请参阅我的问题中的我想要实现的目标部分。
  • @abdou_dev 请看这篇文章,如果你能帮助我? post link
【解决方案2】:

改变这个:

 joinMeetingWin = app.connect(title="Join Meeting", timeout=6)

通过这个:

 joinMeetingWin = app.connect(title="Join", timeout=6)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-10
  • 2017-05-20
  • 1970-01-01
  • 1970-01-01
  • 2017-04-03
  • 2023-03-31
相关资源
最近更新 更多