开发者

Python: Can't continually catch keyboardinterrupt in Windows?

开发者 https://www.devze.com 2023-03-08 06:07 出处:网络
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.

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

精彩评论

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