开发者

Python: Can't continually catch keyboardinterrupt in Windows?

In Python, I wrote the following code to see if I could get my program to not terminate upon Control+C like all those fancy term开发者_运维知识库inal apps such as Vim or Dwarf Fortress.

def getinput():
    x = input('enter something: ')
while True:
    try:
            getinput()
    except KeyboardInterrupt:
            pass

Unfortunately, in the Windows console, this script terminates after a few seconds. If I run it in IDLE, it works as expected. Python version is 3.2.1, 3.2 acted the same. Am I doing something wrong?

EDIT: If I hold down, Control+C, that is.


In order to not terminate on Control-C you need to set a signal handler. From the Python doc here

Python installs a small number of signal handlers by default: SIGPIPE is ignored (so write errors on pipes and sockets can be reported as ordinary Python exceptions) and SIGINT is translated into a KeyboardInterrupt exception. All of these can be overridden.

So you would need to install a signal handler to catch the SIGINT signal and do what you want on that.

The behavior with IDLE is probably that they have a handler installed that blocks the application exit.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜