无法使用 Python 中的“try except”块正确处理与 PYWINAUTO 相关的异常?

Cannot handle PYWINAUTO related exceptions with `try except` block in Python properly?

我的主要目标: 自动化 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>

查看 e 如何在 open_join_meeting_window() 中的 Err before joinMeetingWin: 之后不打印或保持空白。
get_Zoom_Main_Window()

中的 try-except 块也是如此

我曾在 google 寻求帮助,但没有成功。

我想达到什么目的?

最低期望值: 我可以 print() pywinauto 向 console/terminal 提出的错误而不会使我的代码崩溃。
更多期望: 如果可能的话,我可以在我的代码中避免 try-except 块。实施 finding and connecting to the required windowgetting hold of child_window()switching between open windows.

的更好方法

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

看来我已经想出如何在这个 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!!

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

改变这个:

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

通过这个 :

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