Home > database >  How to disable interruption with Ctrl C in cmd/python
How to disable interruption with Ctrl C in cmd/python

Time:02-18

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

CodePudding user response:

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
  • Related