0

I have a simple Python Win32 program that works well when run under pythonw from a command prompt. When I run it under python, it keeps running in the foreground of the command prompt and can e.g. print to STDOUT, which is very useful for debugging. However, it ignores Ctrl-C. I would like to have it exit when Ctrl-C is sent to the console it is running from.

Relevant code is:

    update_gui_thread = threading.Thread(target=gui_clock)
    update_gui_thread.start()
    win32gui.PumpMessages()

def signal_handler(sig, frame):
    print('Ctrl-C pressed, exiting.')
    win32gui.PostQuitMessage(0)
    sys.exit(0)

if __name__ == '__main__':
    signal.signal(signal.SIGINT, signal_handler)
    main()

When I hit Ctrl-C, it prints to Console Ctrl-C pressed, exiting. Python WNDPROC handler failed. The GUI freezes but stays on the screen. Only manually terminating the process via Task Manager make the GUI go away.

I think that most likely the update_gui_thread is exiting but not the main window.

How can I make it exit completely on Ctrl-C?

5
  • Have you tried making the update_gui_thread a daemon? Daemon threads will not prevent a program from exiting. Commented Mar 13 at 23:32
  • Note that in Windows, Ctrl-C is "Copy". Alt-F4" is "Exit application". This has been the case for 40 years now. Commented Mar 14 at 11:39
  • @PaulCornelius Thanks. Making it a daemon thread allowed the exit, but only once the update_gui_thread is awake (see here) Commented Mar 16 at 21:37
  • @MSalters Alt-F4 closes a GUI window; Ctrl-C interrupts a command line (console) app; see Windows docs Commented Mar 16 at 21:38
  • [SO]: How to create a Minimal, Reproducible Example (reprex (mcve)). Commented Mar 19 at 23:26

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.