Tuesday, December 03, 2013

How to make Python raw_input ignores Ctrl-D

The way to do this is to have a while loop around raw_input, and not print the question again in the next iteration. However, because of this Python bug http://bugs.python.org/issue12833, raw_input() or raw_input('') will erase the previous printed question in stdout output with a backspace. A workaround will be needed. Then, there's also a problem with Ctrl-D after you input something... Here's the code to handle Ctrl-D and quit at Ctrl-C without the stacktrace:
import readline
import sys

sys.stdout.write("question? ")
while True:
    try:
        print raw_input(" \b")
        break
    except EOFError:
        pass
    except KeyboardInterrupt:
        break
"import readline" will handle the Ctrl-D when you got something input at the question.

No comments: