Luke Yang
Luke Yang

Reputation: 63

How to catch the stop button in PyCharm on Windows?

I want to create a program that does something in which someone terminates the script by clicking the stop button in PyCharm. I tried

from sys import exit

def handler(signal_received, frame):
    # Handle any cleanup here
    print('SIGINT or CTRL-C detected. Exiting gracefully')
    exit(0)


if __name__ == '__main__':
    signal(SIGINT, handler)

    print('Running. Press CTRL-C to exit.')
    while True:
        # Do nothing and hog CPU forever until SIGINT received.
        pass

from https://www.devdungeon.com/content/python-catch-sigint-ctrl-c.

I tried on both Mac and Windows. On the Mac, PyCharm behaved as expected, when I click the stop button it catches the SIGINT. But on Windows, I did exactly the same thing, but it just straightly returns to me a Process finished with exit code -1. Is there something I can do to change to make the Windows behave like what on Mac?

Any help is appreciated!

Upvotes: 6

Views: 3191

Answers (2)

Elixir
Elixir

Reputation: 31

This actually isnt a simple thing, because PyCharm sends SIGKILL with the stop button. Check the discussion here https://youtrack.jetbrains.com/issue/PY-13316

There is a comment that you can enable "kill windows process softly", however it didnt work for me. The one that does work is emulate terminal in the debug config, then use control c when you select the console window

Upvotes: 3

wz2b
wz2b

Reputation: 1025

I don't think it's a strange question at all. On unix systems, pycham sends a SIGTERM, waits one second, then send a SIGKILL. On windows, it does something else to end the process, something that seems untrappable. Even during development you need a way to cleanly shut down a process that uses native resources. In my case, there is a CAN controller that, if not shut down properly, can't ever be opened again. My work around was to build a simple UI with a stop button that shuts the process down cleanly. The problem is, out of habit, from using pycharm, goland, and intellij, is to just hit the red, square button. Every time I do that I have to reboot the development system. So I think it is clearly also a development time question.

Upvotes: 4

Related Questions