0

I have a Python script for automating simple tasks. Its main loop looks like this:

while True:
  input = download_task_input()
  if input:
    output = process_task(input)
    upload_task_output(output)
  sleep(60)
    

Some local files are altered during task processing. They are modified when the task is started, and restored back to proper state when the task is done, or if exception is caught. Restoring these files on program exit is very important to me: leaving them in altered state causes some trouble later that I'd like to avoid.

When I want to terminate the script, I hit Ctrl+C. It raises KeyboardInterrupt exception which both stops task processing and triggers files restoration. However, if I hit Ctrl+Break, the program is simply terminated: if a task is being processed at this moment, then local files are left in altered state (which is undesirable).

The question: I'm worried about the situation when Windows OS is shutdown by pressing the Power button. Is it possible to make Python handle it exactly like it handles Ctrl+C? I.e. I'd like to detect OS shutdown in Python script and raise Python exception on the main thread.


I know it is possible to call SetConsoleCtrlHandler function from WinAPI and install own handler for situations like Ctrl+C, Ctrl+Break, Shutdown, etc. However, this handler seems to be executed in additional thread, and raising exception in it does not achieve anything. On the other hand, Python itself supposedly uses the same WinAPI feature to raise KeyboardInterrupt on the main thread on Ctrl+C, so it should be doable.

This is not a serious automation script, so I don't mind if a solution is hacky or not 100% reliable.

stgatilov
  • 5,333
  • 31
  • 54
  • I suggest you could refer to the thread:https://stackoverflow.com/questions/1364173/stopping-python-using-ctrlc – Jeaninez - MSFT Apr 13 '22 at 02:17
  • @Jeaninez-MSFT, the referenced question is about how to get Ctrl+Break behavior on pressing Ctrl+C, and it suggests using SetConsoleCtrlHandler to achieve that. I want the opposite: to get Ctrl+C behavior on Ctrl+Break (actually, on OS shutdown). – stgatilov Apr 13 '22 at 04:42
  • Refer to the [Doc](https://learn.microsoft.com/en-us/windows/console/ctrl-c-and-ctrl-break-signals): `CTRL+BREAK` is always treated as a signal. `CTRL+C` behavior in two ways that prevent the handler functions from being called. As far as I'm concerned, you couldn't get Ctrl+C behavior on Ctrl+Break. – Jeaninez - MSFT Apr 19 '22 at 02:24
  • @Jeaninez-MSFT, thanks for a good reference! Do you think Python disables signal on Ctrl+C and handles it as ordinary keyboard input, and thus it can throw exception in the main thread? That would indeed mean that I cannot replicate Python's Ctrl+C behavior on OS shutdown =( – stgatilov Apr 20 '22 at 03:35

0 Answers0