0

for example, there's a code like this:

import signal
import time

def handler(signum, frame):
    print( 'Ctrl+C not allowed')

signal.signal(signal.SIGINT, handler)

for i in range(100):
    a = input("please input a number:")
    if i == a:
        print(i)
    else:
        print(a)
    
print("Finished")

All above codes works fine when running it in Python IDLE even mistakenly "Ctrl+C" are pressed.

The problem is that when running this xx.py file by double clicking it, it shows it is running by py.ext on the window. When I press down "Ctrl+C", the running window disappears right away.(I run it windows 11 system.)

Is there a method to solve this problem please? Many thanks.

BillWoods
  • 1
  • 1
  • 1
    You need to handle the interrupt signal for this: [How do I capture SIGINT in Python?](https://stackoverflow.com/questions/1112343/how-do-i-capture-sigint-in-python) – t.niese Jun 24 '22 at 11:47
  • Thank you very much for your help. I read the link you lead, it seems that handle the interrupt signal can only exit or quit gracefully. – BillWoods Jun 24 '22 at 13:04
  • Why do you assume that? What happens if you don’t call exit when the signal occurs. I never tried in in python, but for any other language that I know it works, so it would be strange if that would be also true for python. – t.niese Jun 24 '22 at 13:09
  • I wrote a for loop to train students to write correct words. If a student try 100 words, so the for loop will be 100 times. However, sometimes this occured: when one has done 90 times, he or she mistakenly pressed Ctrl +C, all data having been done disappeared before those data can be written into a document and stored. – BillWoods Jun 24 '22 at 13:39
  • I just did a test with your code combined with [this answer](https://stackoverflow.com/questions/1112343/how-do-i-capture-sigint-in-python/1112363#1112363) and as I expected it works perfectly fine. – t.niese Jun 24 '22 at 13:54
  • Thank you so much! When I run the codes after adding the codes you leads, it works in Python IDLE. – BillWoods Jun 24 '22 at 14:24
  • However, when I run this XX.py document by double clicking it, and then input numbers, it works fine. while I press the "Ctrl+C" again, the running window disappears right away. How can I solve this problem when double clicking to run it? Thanks again :) – BillWoods Jun 24 '22 at 14:32

0 Answers0