KeyboardInterrupt taking a while

[亡魂溺海] 提交于 2020-01-03 10:02:16

问题


So I just started messing around with Python on Linux, using Tkinter. I'm trying to make Cntrl+C stop execution by using the KeyboardInterrupt Exception, but when i press it nothing happens for a while. Eventually it "takes" and exits. A little bit of reading suggests this might have to do with threading or something, but i'm so new to this stuff i'm really not sure where to begin.

#! /usr/bin/python
import sys
from Tkinter import *

try: 
    root = Tk()
    root.mainloop()
except:
    print "you pressed control c"
    sys.exit(0)

I hate to be the noob that only wants the quick-fix, so if your answer is as simple as pointing me to the right documentation, that'd be wonderful.


回答1:


That is a little problematic because, in a general way, after you invoke the mainloop method you are relying on Tcl to handle events. Since your application is doing nothing, there is no reason for Tcl to react to anything, although it will eventually handle other events (as you noticed, this may take some time). One way to circumvent this is to make Tcl/Tk do something, scheduling artificial events as in:

from Tkinter import Tk

def check():
    root.after(50, check) # 50 stands for 50 ms.

root = Tk()
root.after(50, check)
root.mainloop()



回答2:


According to Guido van Rossum, this is because you are stuck in the Tcl/Tk main loop, while the signal handlers are only handled by the Python interpreter.

You can work around the problem, by binding Ctrl-c to a callback function:

import sys
import Tkinter as tk

def quit(event):
    print "you pressed control c"
    root.quit()

root = tk.Tk()
root.bind('<Control-c>', quit)
root.mainloop()


来源:https://stackoverflow.com/questions/13784232/keyboardinterrupt-taking-a-while

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!