首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不能正确处理Python中与“尝试除外”块有关的PYWINAUTO异常吗?

不能正确处理Python中与“尝试除外”块有关的PYWINAUTO异常吗?
EN

Stack Overflow用户
提问于 2021-10-18 09:18:53
回答 2查看 756关注 0票数 2

我的主要目标:自动化缩放

我的zoomModule.py文件是:

代码语言:javascript
复制
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")

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

代码语言:javascript
复制
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中的Err before joinMeetingWin:之后,open_join_meeting_window()是如何不被打印或保持空白的。

同样的情况发生在get_Zoom_Main_Window()内部的get_Zoom_Main_Window()块中。

我曾在谷歌寻求帮助,但徒劳无功。

我想实现什么?

最小期望:,我可以在不破坏代码的情况下将pywinauto引发的错误发送到控制台/终端。

更多的期望:如果可能的话,可以避免代码中的try-except块。更好地实现了finding and connecting to the required windowgetting hold of child_window()switching between open windows的方式。

我的方法可能是错的。那样的话,请给我看看正确的程序。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-10-18 15:28:08

似乎我已经想出了如何在这个print() the errors raised by pywinauto to the console/terminal without crashing my code的帮助下实现回答

open_join_meeting_window函数-↓↓↓之前的

代码语言:javascript
复制
# 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函数-修改后的↓↓↓

代码语言:javascript
复制
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

新终端日志↓↓↓

代码语言:javascript
复制
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引发的错误的名称来决定要做什么。

票数 2
EN

Stack Overflow用户

发布于 2021-10-20 13:14:11

改变这一点:

代码语言:javascript
复制
 joinMeetingWin = app.connect(title="Join Meeting", timeout=6)

通过这一点:

代码语言:javascript
复制
 joinMeetingWin = app.connect(title="Join", timeout=6)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69613613

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档