如何阻止警告对控制Python程序的执行产生影响?
我正在使用Win32GUI和Watsup,写一些Python代码来自动化在一个没有界面的程序中搜索数据库。简单来说,我可以从一个列表中取出一个字符串,然后把它输入到搜索框里,点击“查找”。
不过,当搜索结果超过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)
1 个回答
我不是WATSUP的用户,但我用pywinauto做了类似的事情。我的情况是,我在运行一些自动化测试,这些测试会打开各种第三方程序,而这些程序也会弹出一些烦人的警告对话框。处理那些你不知道会出现的对话框有点困难,不过如果你知道会出现哪些对话框,但不知道它们什么时候出现,你可以启动一个线程来专门处理这些弹窗。下面是我正在做的一个简单示例,使用了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做了类似的事情,但没有使用线程,也就是,它会寻找一个特定名字的窗口,并点击那个窗口上的一个特定按钮。