使用 Win32GUI 和 Watsup ,我正在编写一些 Python 代码来自动执行跨数据库的搜索,该数据库是通过不附带接口(interface)的程序访问的。因此,我可以从列表中取出一个字符串,然后将其输入到搜索框中并按“查找”。
但是,当搜索返回超过 1000 个结果时,程序会抛出一个警告对话框(这只是结果数量的通知),从而停止 Python 代码的执行。我无法让代码继续执行按查找的行。
据猜测,这是因为它不期望有一个窗口或不知道如何处理警告 - 但我也不知道,除了手动接受它。下面是相关的代码示例,尽管它可能不是很有启发。在“clickButton(LookupButton)”之后,执行停止。
LookupButtonlocation = elemstring.find("Lookup", AuthNameFieldlocation) - 15
#Use Regex search to find handles
number_regex = re.compile(';(\d+);')
AuthNameEdit = int(number_regex.search(elemstring[AuthNameFieldlocation:]).group(1))
LookupButton = int(number_regex.search(elemstring[LookupButtonlocation:]).group(1))
#Input new Author into Edit Field
setEditText(AuthNameEdit, "John Campbell")
#Click lookup button
clickButton(LookupButton)
最佳答案
我不是 WATSUP 用户,但我使用 pywinauto 做了一些非常类似的事情 - 在我的例子中,我正在运行许多自动化测试,这些测试打开各种第 3 方程序,这些程序以类似的方式抛出不方便的警告对话框。处理您不知道的对话框有点困难,但是如果您确实知道出现了哪些对话框,但不知道它们出现的时间,您可以启动一个线程来处理那些弹出的对话框。 UPS。以下是我正在做的一个简单示例,并使用 pywinauto,但您可以调整 WATSUP 的方法:
import time
import threading
class ClearPopupThread(threading.Thread):
def __init__(self, window_name, button_name, quit_event):
threading.Thread.__init__(self)
self.quit_event = quit_event
self.window_name = window_name
self.button_name = button_name
def run(self):
from pywinauto import application, findwindows
while True:
try:
handles = findwindows.find_windows(title=self.window_name)
except findwindows.WindowNotFoundError:
pass #Just do nothing if the pop-up dialog was not found
else: #The window was found, so click the button
for hwnd in handles:
app = application.Application()
app.Connect(handle=hwnd)
popup = app[self.window_name]
button = getattr(popup, self.button_name)
button.Click()
if self.quit_event.is_set():
break
time.sleep(1) #should help reduce cpu load a little for this thread
本质上,这个线程只是一个无限循环,它按名称查找弹出窗口,如果找到,则单击按钮关闭窗口。如果您有许多弹出窗口,则可以为每个弹出窗口打开一个线程(但效率不太高)。因为它是一个无限循环,所以我让线程查看是否设置了事件,以允许我从主程序停止线程。因此,在主程序中我做了这样的事情:
#Start the thread
quit_event = threading.Event()
mythread = ClearPopupThread('Window Popup Title', 'Yes button', quit_event)
# ...
# My program does it's thing here
# ...
# When my program is done I need to end the thread
quit_event.set()
这不一定是解决您的问题的唯一方法,但对我来说是一种有效的方法。抱歉,我在处理 WATSUP 方面无法真正帮助您(我总是发现 pywinauto 更容易使用),但我在 WATSUP 主页( http://www.tizmoi.net/watsup/intro.html )上注意到,示例 2 在不使用线程的情况下做了类似的事情,即,看起来对于命名窗口并单击该窗口上的特定按钮。
关于python - 如何阻止警告对话框停止执行控制它的 Python 程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5774506/