You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让xlwings在Excel文件被他人占用时暂停并重试?

问题:Excel文件被他人占用时,Python脚本如何自动重试打开?

我们共用一台服务器,Excel文件被他人占用时其他用户无法打开。我用Python脚本提升效率,但需要打开一个常被使用的Excel文件,执行脚本时如果文件被占用会触发如下错误:

return self._oleobj_.InvokeTypes(3174, LCID, 1, (24, 0), ((12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (3, 49), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17)),Filename
pywintypes.com_error: (-2147352567, 'Er is een uitzondering opgetreden.', (0, 'Microsoft Excel', 'Kan geen toegang krijgen tot PythonTest.xlsm.', 'xlmain11.chm', 0, -2146827284), None)

翻译后提示:发生异常,无法访问PythonTest.xlsm。

我希望脚本尝试打开文件时,若遇到占用则暂停几秒后重试,现有代码如下:

import xlwings
import time

excel_file = xlwings.Book("my_file_path")

# while excel_file is opened by other user:
#     time.sleep(5)
#     try again to open the Excel file

解决方案

通过try-except捕获pywintypes.com_error异常,结合循环即可实现自动重试逻辑,以下是两种实用实现方式:

方式1:无限重试(直到文件可打开)

适合需要确保最终打开文件的场景,会持续尝试直到成功:

import xlwings
import time
from pywintypes import com_error

file_path = "my_file_path"
retry_interval = 5  # 每次重试间隔5秒

while True:
    try:
        excel_file = xlwings.Book(file_path)
        print("文件打开成功")
        break  # 成功打开后跳出循环
    except com_error as e:
        # 匹配文件被占用的错误特征
        error_code = e.args[0]
        error_msg = e.args[2][2]
        if error_code == -2147352567 or "无法访问" in error_msg or "Kan geen toegang krijgen tot" in error_msg:
            print(f"文件被占用,{retry_interval}秒后重试...")
            time.sleep(retry_interval)
        else:
            # 其他COM异常直接抛出,不重试
            raise e

方式2:带最大重试次数的重试

避免脚本无限挂起,设置最大尝试次数,超过后停止:

import xlwings
import time
from pywintypes import com_error

file_path = "my_file_path"
retry_interval = 5  # 每次重试间隔5秒
max_retries = 10    # 最大重试次数

for attempt in range(max_retries):
    try:
        excel_file = xlwings.Book(file_path)
        print(f"文件打开成功,共尝试{attempt+1}次")
        break
    except com_error as e:
        error_code = e.args[0]
        error_msg = e.args[2][2]
        if error_code == -2147352567 or "无法访问" in error_msg or "Kan geen toegang krijgen tot" in error_msg:
            if attempt < max_retries - 1:
                print(f"文件被占用,第{attempt+1}次尝试失败,{retry_interval}秒后重试...")
                time.sleep(retry_interval)
            else:
                print(f"已达到最大重试次数{max_retries}次,文件仍无法打开")
                raise e  # 超过次数后抛出异常,也可根据需求改为自定义处理逻辑
        else:
            raise e

关键说明

  • 捕获异常后通过错误代码(-2147352567)或错误提示信息精准判断是否为文件被占用的情况,避免误处理其他COM异常。
  • 两种方式可根据实际业务需求选择,带次数限制的重试更适合需要容错边界的场景。

内容的提问来源于stack exchange,提问作者Pascal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 22:40:44