I have the following code running on Python 3.9.0 on a windows 10 machine.
Plan is to exit from the while loop and exit gracefully,It should print some message here 'hello'and exit.
import signal # Import signal module using the import keyword
import time
# available signalson our System
valid_signals = signal.valid_signals() #requires python3.9.0
print(valid_signals)
#create a Signal Handler
def SignalHandler(SignalNumber,Frame):
print('hello')
print(f'Signal Number -> {SignalNumber} Frame -> {Frame} ')
signal.signal(signal.SIGINT,SignalHandler)
while 1:
print("Press Ctrl C")
time.sleep(1)
When i run this, I am getting this KeyboardInterrupt: Execution interrupted strong text here is the output of the script
Python 3.9.0 (C:\Python\python.exe)
>>> %Run Python-.py
{<Signals.SIGINT: 2>, <Signals.SIGILL: 4>, <Signals.SIGFPE: 8>, <Signals.SIGSEGV: 11>, <Signals.SIGTERM: 15>, <Signals.SIGBREAK: 21>, <Signals.SIGABRT: 22>}
Press Ctrl C
Press Ctrl C
Press Ctrl C
Press Ctrl C
Press Ctrl C
Press Ctrl C
Press Ctrl C
Press Ctrl C
Press Ctrl C
Press Ctrl C
Press Ctrl C
Press Ctrl C
Press Ctrl C
Traceback (most recent call last):
File "E:\_1_Personal\MY PROJECTS\SourceCodes\Python3-Tutorial\Python-.py", line 18, in <module>
time.sleep(1)
File "C:\Thonny\lib\site-packages\thonny\backend.py", line 346, in signal_handler
raise KeyboardInterrupt("Execution interrupted")
KeyboardInterrupt: Execution interrupted
>>>
Why is the code not going to the Signal handler and printing hello?
CodePudding user response:
Issue was with the IDE ,Thonny and IDLE When i tried running the code on command line directly,
C:> python Abovepythoncode.py
No issues were found
CodePudding user response:
try this and put your code in try
block, And when you press CTRL C then exception will occure
try:
# main code here
except KeyboardInterrupt:
print ('KeyboardInterrupt exception is caught')
else:
print ('No exceptions are caught')