Search code examples
pythonexcelprompttaskkill

How to initiate a 'Do not Save' command along with os.system('taskkill') in Python


The project I am working on will create a .CSV file for the user to look at if needed.

If my script tries to open the .CSV file while the user has the file open in excel, my script will initiate os.system("taskkill /im EXCEL.EXE"). This closes Excel program so that my script can write to the file since the logging is more important than the file being open.

My issue and where I need help is this: If the user has changed ANYTHING in the excel file while it is opened, when the taskkill command is sent, excel prompts "would you like to save?". So my script continues to initiate the taskill command over and over until either Excel, or my script crashes.

QUESTIONS:

1.How can I let my script know when this prompt occurs?

2.How can I tell Excel "No Do Not Save" using python script, if this prompt occurs?

This is the function I am referring to:

def unlockDoor(x, y):
    userDictionary = shelve.open(UserDict)
    print('Welcome,',userDictionary[x])
    print('Door Unlocked')
    while True:
        try:
            with open(EntryLog, "a") as log:
                log.write("{0},{1},{2},{3}\n".format(time.strftime("%Y-%m-%d %H:%M:%S"), x, userDictionary[x],y))
                userDictionary.close()
                break
        except:
            os.system("taskkill /im EXCEL.EXE")

Solution

  • You're really not going about this right.

    First, as the taskkill docs explain, you can use the /f flag to forcefully terminate the process. This will prevent it from popping up any "Save?" or "Are you sure?" dialogs, or anything else, and just kill it.

    But really, you shouldn't be using taskkill (and especially not via os.system instead of subprocess) instead of just doing it in Python. Using external tools makes sense in some cases—e.g., if you're a wizard with taskkill but know nothing about the os module or the third-party psutil module. But that obviously isn't the case here, or you would have known about /f, or at least known how to search for it.

    Meanwhile, if you want to interact with the Excel GUI, you need to use a GUI automation library (like pyautogui).

    Or, even better, use pywin32 to automate Excel via COM. pywin32 comes with nice documentation, including samples for driving Excel.