[Solved] – Python – How do I capture SIGINT in Python?

How do I capture SIGINT in Python?

Asked on October 16, 2018 in Python.
Add Comment

  • 3 Answer(s)

    You can treat it like associate exception (KeyboardInterrupt), like all different. create a brand new file and run it from your shell with the subsequent contents to envision what I mean:

    import time, sys
    x = 1
    while True:
            print x
            x += 1
        except KeyboardInterrupt:
            print "Bye"
    Answered on October 16, 2018.
    Add Comment

    Register your handler with signal.signal like this:

    #!/usr/bin/env python
    import signal
    import sys
    def signal_handler(sig, frame):
            print('You pressed Ctrl+C!')
    signal.signal(signal.SIGINT, signal_handler)
    print('Press Ctrl+C')
    Answered on February 9, 2019.
    Add Comment
    import signal
    # store default handler of signal.SIGINT
    default_handler = signal.getsignal(signal.SIGINT)
    catch_count = 0
    def handler(signum, frame):
        global default_handler, catch_count
        catch_count += 1
        print ('wait:', catch_count)
        if catch_count > 3:
            # recover handler for signal.SIGINT
            signal.signal(signal.SIGINT, default_handler)
            print('expecting KeyboardInterrupt')
    signal.signal(signal.SIGINT, handler)
    print('Press Ctrl+c here')
    while True:
    Answered on February 20, 2019.
    Add Comment

  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.