问题
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