2011-04-25 50 views
1

使用Win32GUI和Watsup,我正在编写一段Python代码来自动执行跨数据库的搜索,该数据库可以通过未附带接口的程序访问。因此,我可以从列表中获取一个字符串,然后将其输入到搜索框并按'查找'。如何阻止警告对话框停止执行控制它的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在不使用线程的情况下做了类似的事情,即寻找命名窗口并单击该窗口上的特定按钮。