利用python进行excel自动化操作的过程中,尤其是涉及vba时,可能遇到消息框/弹窗(msgbox)。此时需要人为响应,否则代码卡死直至超时 [^1] [^2]。根本的解决方法是vba代码中不要出现类似弹窗,但有时我们无权修改被操作的excel文件,例如这是我们进行自动化测试的对象。所以本文记录从代码角度解决此类问题的方法。

假想场景

使用xlwings(或者其他自动化库)打开excel文件test.xlsm,读取sheet1!a1单元格内容。很简单的一个操作:

import xlwings as xw

wb = xw.book('test.xlsm')
msg = wb.sheets('sheet1').range('a1').value
print(msg)
wb.close()

然而不幸的是,打开工作簿时进行了热情的欢迎仪式:

private sub workbook_open()
    msgbox "welcome"
    msgbox "to open"
    msgbox "this file."
end sub

第一个弹窗welcome就卡住了excel,python代码相应卡死在第一行。

基本思路

主程序中不可能直接处理或者绕过此类问题,也不能奢望有人随时蹲守点击下一步——那就开启一个子线程来护航吧。因此,解决方案是利用子线程监听并随时关闭弹窗,直到主程序圆满结束。
解决这个问题,需要以下两个知识点(基础知识请课外学习):

  • python多线程(本文采用threading.thread)
  • python界面自动化库(本文涉及pywinauto和pywin32)

pywinauto方案

pywinauto顾名思义是windows界面自动化库,模拟鼠标和键盘操作窗体和控件 [^3]。不同于先获取句柄再获取属性的传统方式,pywinauto的api更加友好和pythonic。例如,两行代码搞定窗口捕捉和点击:

from pywinauto.application import application

win = application(backend="win32").connect(title='microsoft excel')
win.dialog.button.click()

本文采用自定义线程类的方式,启动线程后自动执行run()函数来完成上述操作。具体代码如下,注意构造函数中的两个参数:

  • title 需要捕捉的弹窗的标题,例如excel默认弹窗的标题为microsoft excel
  • interval 监听的频率,即每隔多少秒检查一次
# listener.py

import time
from threading import thread, event
from pywinauto.application import application


class msgboxlistener(thread):

    def __init__(self, title:str, interval:int):
        thread.__init__(self)
        self._title = title 
        self._interval = interval 
        self._stop_event = event()   

    def stop(self): self._stop_event.set()

    @property
    def is_running(self): return not self._stop_event.is_set()

    def run(self):
        while self.is_running:
            try:
                time.sleep(self._interval)
                self._close_msgbox()
            except exception as e:
                print(e, flush=true)


    def _close_msgbox(self):
        '''close the default excel msgbox with title "microsoft excel".'''        
        win = application(backend="win32").connect(title=self._title)
        win.dialog.button.click()


if __name__=='__main__':
    t = msgboxlistener('microsoft excel', 3)
    t.start()
    time.sleep(10)
    t.stop()

于是,整个过程分为三步:

  • 启动子线程监听弹窗
  • 主线程中打开excel开始自动化操作
  • 关闭子线程
import xlwings as xw
from listener import msgboxlistener

# start listen thread
listener = msgboxlistener('microsoft excel', 3)
listener.start()

# main process as before
wb = xw.book('test.xlsm')
msg = wb.sheets('sheet1').range('a1').value
print(msg)
wb.close()

# stop listener thread
listener.stop()

到此问题基本解决,本地运行效果完全达到预期。但我的真实需求是以系统服务方式在服务器上进行excel文件自动化测试,后续发现,当以系统服务方式运行时,pywinauto竟然捕捉不到弹窗!这或许是pywinauto一个潜在的问题 [^4]。

win32gui方案

那就只好转向相对底层的win32gui,所幸完美解决了上述问题。
win32gui是pywin32库的一部分,所以实际安装命令是:

pip install pywin32

整个方案和前文描述完全一致,只是替换msgboxlistener类中关闭弹窗的方法:

import win32gui, win32con

def _close_msgbox(self):
    # find the top window by title
    hwnd = win32gui.findwindow(none, self._title)
    if not hwnd: return

    # find child button
    h_btn = win32gui.findwindowex(hwnd, none,'button', none)
    if not h_btn: return

    # show text
    text = win32gui.getwindowtext(h_btn)
    print(text)

    # click button        
    win32gui.postmessage(h_btn, win32con.wm_lbuttondown, none, none)
    time.sleep(0.2)
    win32gui.postmessage(h_btn, win32con.wm_lbuttonup, none, none)
    time.sleep(0.2)

更一般的方案

更一般地,当同时存在默认标题和自定义标题的弹窗时,就不便于采用标题方式进行捕捉了。例如

msgbox "message with default title.", vbinformation, 
msgbox "message with title my app 1", vbinformation, "my app 1"
msgbox "message with title my app 2", vbinformation, "my app 2"

那就扩大搜索范围,依次点击所有包含确定性描述的按钮(例如ok,yes,confirm)来关闭弹窗。同理替换msgboxlistener类的_close_msgbox()方法(同时构造函数中不再需要title参数):

def _close_msgbox(self):
    '''click any button ("ok", "yes" or "confirm") to close message box.'''
    # get handles of all top windows
    h_windows = []
    win32gui.enumwindows(lambda hwnd, param: param.append(hwnd), h_windows) 

    # check each window    
    for h_window in h_windows:            
        # get child button with text ok, yes or confirm of given window
        h_btn = win32gui.findwindowex(h_window, none,'button', none)
        if not h_btn: continue

        # check button text
        text = win32gui.getwindowtext(h_btn)
        if not text.lower() in ('ok', 'yes', 'confirm'): continue

        # click button
        win32gui.postmessage(h_btn, win32con.wm_lbuttondown, none, none)
        time.sleep(0.2)
        win32gui.postmessage(h_btn, win32con.wm_lbuttonup, none, none)
        time.sleep(0.2)

最后,实例演示结束全文,以后再也不用担心意外弹窗了。

以上就是如何用 python 子进程关闭 excel 自动化中的弹窗的详细内容,更多关于python 子进程关闭 excel 弹窗的资料请关注www.887551.com其它相关文章!