Python, How to close excel workbook if user prematurely closes the command prompt?

风流意气都作罢 提交于 2021-01-28 08:52:12

问题


Using Windows, I start a command prompt and run my script, which will open an excel file in the background. I do use a try/except/finally block to catch exceptions and finally close the workbook, but it seems that if I hit the red 'X' on the command prompt (before the code completely finishes running) that the excel workbook stays open.

My best guess is that the code just completely stops executing, wherever it was at?

This isn't completely uncommon for me to do. What happens is that I realize I missed a previous step and so I just want to close the command prompt and the workbook that resides in the background.

I initially expected that try/except/finally would cover this case:

try:
        xl = win32com.client.Dispatch("Excel.Application")
        wb = xl.Workbooks.Open(Filename=file)
        # Do stuff
        # Close out of command prompt while doing stuff
except Exception as e:
        print(e)
finally:
        wb.Close(SaveChanges=0) # doesn't seem to close out of the workbook 
                                # when command prompt forcefully closed

When that failed, I've looked for similar issues elsewhere, and tried the 'atexit' module, which also doesn't seem to work.

What is the correct way to close out of the excel workbook, if the user cancels the command prompt?


回答1:


Let's see....

try:
    xl = win32com.client.Dispatch("Excel.Application")
    wb = xl.Workbooks.Open(Filename=file)
    # Do stuff
    # Close out of command prompt while doing stuff
except Exception as e:
    print(e)
finally:
    wb.Close(SaveChanges=0) # doesn't seem to close out of the workbook 
                            # when command prompt forcefully closed

The question needs a little more context but from what I can tell try this:

import os

cmd = os.system("start /wait cmd /c {command}")
try:
    xl = win32com.client.Dispatch("Excel.Application")
    wb = xl.Workbooks.Open(Filename=file)
    # Do stuff
    os_close = os.close()
    try:
        os_close
        wb.close(SaveChanges=0)
    except NameError:
        continue

except Exception as e:
    print(e)

The 'finally' doesn't work very well there because the computer does not know when to execute the finally and might not close wb.

Again, very little context.



来源:https://stackoverflow.com/questions/55552062/python-how-to-close-excel-workbook-if-user-prematurely-closes-the-command-promp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!