Search code examples
pythonpywinauto

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


My main goal: Automating Zoom

my zoomModule.py file is:

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")

Terminal, when I run the above file:

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>

See how e does not get printed or remain blank after Err before joinMeetingWin: in the open_join_meeting_window().
The same happens for the try-except block inside the get_Zoom_Main_Window()

I have looked for help in google, but in vain.

What I want to achieve?

Minimum expectation: I can print() the errors raised by pywinauto to the console/terminal without crashing my code.
More expectation: I can avoid try-except blocks in my code if possible. Implement better way of finding and connecting to the required window, getting hold of child_window() and switching between open windows.

My approach may be wrong. In that case please show me the correct procedure.


Solution

  • Seems like I have figured out how to print() the errors raised by pywinauto to the console/terminal without crashing my code with the help of this answer.

    open_join_meeting_window function - Before ↓↓↓

    # 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 function - after modification ↓↓↓

    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
    

    New terminal logs↓↓↓

    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!!
    

    First, the traditional traceback is printed. Then the name of the error raised by pywinauto is used in the control-flow to decide what to do.