1

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 terminal 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.

2
  • 1
    Works for me on Windows console, Python 3.2. What are you expecting to happen and what actually happens? What error is raised? Commented May 23, 2011 at 16:40
  • I edited the answer to be clearer. If I hold down Control+C, in the console it terminates without an error, whereas IDLE performs as expected and keeps displaying 'enter something: '. Commented May 23, 2011 at 17:23

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The interactive interpreter from Windows' command line works without issues as well, so that all makes sense. Thanks for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.