Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to know if it's possible to catch a Control-C in python in the following manner:

 if input != contr-c:
    #DO THINGS
 else:
    #quit

I've read up on stuff with try and except KeyboardInterrupt but they're not working for me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
699 views
Welcome To Ask or Share your Answers For Others

1 Answer

Consider reading this page about handling exceptions.. It should help.

As @abarnert has said, do sys.exit() after except KeyboardInterrupt:.

Something like

try:
    # DO THINGS
except KeyboardInterrupt:
    # quit
    sys.exit()

You can also use the built in exit() function, but as @eryksun pointed out, sys.exit is more reliable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...