Detect keyboard interrupter when exiting context manager

How can I detect Python is being keyboard interrupted when exiting the context menu.
def exit is triggered, but I do not know how to detect keyboard interrupted .

except is not working without “try”, signal module seems bit complicated.
Is there a way/variable to check if the code is exiting because of Keyboard Interrupt?

import os
class TestContext():
    def __init__(self, file=''):
        self.temp1 = "foo"

    def __enter__(self):
        print("Entering Context Manager")
        return self.temp1

    def __exit__(self, type, value, traceback):
        self.temp1 = "Exiting Context Manager"
        print("Exiting Context Manager")

        # except KeyboardInterrupt:
        #   print("catch keyboard interrype")

filePath = ""

with TestContext(filePath) as x:
    print("press ctrl+c for interruption")
    while True:

Try this and see if it gives some insight:

class TestCM(object):
    def __enter__(self):
        print("Entering Context Manager")
        return self
    def __exit__(self, type, value, traceback):
        print("Caught exception:", type, "value:", repr(value))
        return True

import time
with TestCM() as cm:
    time.sleep(300000)  # Ctrl-C to exit

1 Like

Did not realize there are variables in the function.

Thanks you your script.