如何用 Python 子进程关闭 Excel 自动化中的弹窗


Posted in Python onMay 07, 2021

利用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 子进程关闭 Excel 自动化中的弹窗

基本思路

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

  • 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 自动化中的弹窗的详细内容,更多关于Python 子进程关闭 Excel 弹窗的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
Python计算程序运行时间的方法
Dec 13 Python
浅谈机器学习需要的了解的十大算法
Dec 15 Python
Python入门之后再看点什么好?
Mar 05 Python
python实现反转部分单向链表
Sep 27 Python
Python神奇的内置函数locals的实例讲解
Feb 22 Python
django 使用全局搜索功能的实例详解
Jul 18 Python
pytorch 可视化feature map的示例代码
Aug 20 Python
Python Gitlab Api 使用方法
Aug 28 Python
python 装饰器功能与用法案例详解
Mar 06 Python
django修改models重建数据库的操作
Mar 31 Python
django 解决自定义序列化返回处理数据为null的问题
May 20 Python
python 爬取英雄联盟皮肤并下载的示例
Dec 04 Python
PyTorch的Debug指南
May 07 #Python
基于Python的EasyGUI学习实践
Python列表删除重复元素与图像相似度判断及删除实例代码
使用python如何删除同一文件夹下相似的图片
May 07 #Python
python学习之panda数据分析核心支持库
Python基于Tkinter开发一个爬取B站直播弹幕的工具
May 06 #Python
Python爬虫之爬取最新更新的小说网站
May 06 #Python
You might like
PHP的面试题集
2006/11/19 PHP
php中防止伪造跨站请求的小招式
2011/09/02 PHP
yii实现CheckBox复选框在同一行显示的方法
2014/12/03 PHP
PHP 序列化和反序列化函数实例详解
2020/07/18 PHP
jQuery textarea的长度进行验证
2009/05/06 Javascript
JavaScript中获取元素索引的函数
2010/09/10 Javascript
javascript取消文本选定的实现代码
2010/11/14 Javascript
ajax更新数据后,jquery、jq失效问题
2011/03/16 Javascript
在新窗口打开超链接的方法小结
2013/04/14 Javascript
自己编写的类似JS的trim方法
2013/10/09 Javascript
用js代码改变单选框选中状态的简单实例
2013/12/18 Javascript
再探JavaScript作用域
2014/09/24 Javascript
理解javascript定时器中的setTimeout与setInterval
2016/02/23 Javascript
jquery实现左右无缝轮播图
2020/07/31 Javascript
详解Javascript获取缓存和清除缓存API
2017/05/25 Javascript
vue input输入框模糊查询的示例代码
2018/05/22 Javascript
Bootstrap 实现表格样式、表单布局的实例代码
2018/12/09 Javascript
微信小程序云开发详细教程
2019/05/16 Javascript
详解vue-cli@2.x项目迁移日志
2019/06/06 Javascript
vue实现图片按比例缩放问题操作
2020/08/11 Javascript
jQuery实现二级导航菜单的示例
2020/09/30 jQuery
Python中threading模块join函数用法实例分析
2015/06/04 Python
同时安装Python2 & Python3 cmd下版本自由选择的方法
2017/12/09 Python
python编程实现随机生成多个椭圆实例代码
2018/01/03 Python
Python利用字典破解WIFI密码的方法
2019/02/27 Python
Python图像处理库PIL的ImageFont模块使用介绍
2020/02/26 Python
pandas数据处理之绘图的实现
2020/06/15 Python
css3中背景尺寸background-size详解
2014/09/02 HTML / CSS
HTML5+CSS设置浮动却没有动反而在中间且错行的问题
2020/05/26 HTML / CSS
澳大利亚排名第一的狂热牛仔品牌:ONETEASPOON
2018/11/20 全球购物
给水排水工程专业毕业生推荐信
2013/10/28 职场文书
外企财务年会演讲稿
2014/01/03 职场文书
征兵宣传标语
2014/06/20 职场文书
经营目标管理责任书
2014/07/25 职场文书
演讲稿开场白台词
2014/08/25 职场文书
部队2015年终工作总结
2015/04/02 职场文书