2

I have a program that has quite a few functions, each running on a separate thread. When the user presses Ctrl+C, only 1 thread crashes with an exception, but because of this, the whole program may not work correctly.

Of course, I can write this construction in each function:

try:
    do_something()
except KeyboardInterrupt as e:
    pass

but, as I said, there are many functions, perhaps there is an option not to prescribe this construction in each function?

Or is it possible to disable Ctrl+C interrupt in cmd settings? For example, in the registry. The program creates its own registry key in HKEY_CURRENT_USER\Console\MyProgrammKey

UPD 1

signal.signal(signal.SIGINT, signal.SIG_IGN)

It helped in almost all cases except one: a thread that has an infinite loop with the input() function anyway interrupts.

UPD 2

Here is a sample code

import signal, time
from threading import Thread


def one():
    while True:
        inp = input("INPUT: ")


def two():
    while True:
        print("I just printing...")
        time.sleep(1)


if __name__ == '__main__':
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    Thread(target=one).start()
    Thread(target=two).start()

UPD 3

Screenshot of exception. enter image description here

1 Answers1

3

Ctrl+C will send SIGINT signal to program, so you could define a global signal handler to ignore that SIGINT, something like next:

test.py:

import signal, os, time

def handler(signum, frame):
    pass

signal.signal(signal.SIGINT, handler)

time.sleep(10)

print("done")

During the program run, if you input Ctrl+c, the program will ignore it, and continue to run, finally print done:

$ python3 test.py
^Cdone
atline
  • 28,355
  • 16
  • 77
  • 113
  • 2
    [`SIG_IGN` might be better](https://stackoverflow.com/a/842807/18238422) – Pychopath Feb 18 '22 at 02:19
  • @Pychopath Sure, if we no need do anything in handler. – atline Feb 18 '22 at 02:21
  • @atline, thanks, it helped in almost all cases except one: a thread that has an infinite loop with the input() function anyway interrupts. –  Feb 18 '22 at 02:29
  • @Mus1k Would you show the minimal code? – atline Feb 18 '22 at 02:32
  • @atline, updated. –  Feb 18 '22 at 02:38
  • @Msu1k Er... what's the running result on your side, it still works perfectly on my side using the same code your affords... How you judge it not work? – atline Feb 18 '22 at 02:41
  • @atline, updated again. –  Feb 18 '22 at 02:46
  • 1
    @Mus1k YES, the difference is you use windows, while I'm using linux. It looks ok on linux. So what I suggest is wrap try...except around input, if you are using windows. You can't find a proper way to `except KeyBoardInterrupt` because there so many functions, but I think it's easy to `except EOFError` as you are sure to know where you use `input()`... – atline Feb 18 '22 at 03:23