From 73441e41c14d8bc086ad5db7c5ba5b83cbd08991 2013-11-15 00:40:54 From: Paul Ivanov Date: 2013-11-15 00:40:54 Subject: [PATCH] custom keyboard interrupt handling in ask_yes_no Sometimes, Ctrl-C just makes sense as an answer, and re-asking the question is just frustrating. This changes makes it possible to break out of the asking loop via Ctrl-C. This is particularly handy for asking questions from the command line, where one expects Ctrl-c to be a sort of "Cancel" operation, and is often functionally equivalent to "no" --- diff --git a/IPython/utils/io.py b/IPython/utils/io.py index 46296be..088c5be 100644 --- a/IPython/utils/io.py +++ b/IPython/utils/io.py @@ -155,11 +155,13 @@ class Tee(object): self.close() -def ask_yes_no(prompt,default=None): +def ask_yes_no(prompt, default=None, interrupt=None): """Asks a question and returns a boolean (y/n) answer. If default is given (one of 'y','n'), it is used if the user input is - empty. Otherwise the question is repeated until an answer is given. + empty. If interrupt is given (one of 'y','n'), it is used if the user + presses Ctrl-C. Otherwise the question is repeated until an answer is + given. An EOF is treated as the default answer. If there is no default, an exception is raised to prevent infinite loops. @@ -174,7 +176,8 @@ def ask_yes_no(prompt,default=None): if not ans: # response was an empty string ans = default except KeyboardInterrupt: - pass + if interrupt: + ans = interrupt except EOFError: if default in answers.keys(): ans = default