Ask a yes/no question via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits . It must be "yes" (the default), "no" or None (meaning an answer is required of the user).
(question, default="yes")
| 473 | |
| 474 | ## {{{ http://code.activestate.com/recipes/577058/ (r2) |
| 475 | def query_yes_no(question, default="yes"): |
| 476 | """Ask a yes/no question via raw_input() and return their answer. |
| 477 | |
| 478 | "question" is a string that is presented to the user. |
| 479 | "default" is the presumed answer if the user just hits <Enter>. |
| 480 | It must be "yes" (the default), "no" or None (meaning |
| 481 | an answer is required of the user). |
| 482 | |
| 483 | The "answer" return value is one of "yes" or "no". |
| 484 | """ |
| 485 | valid = {"yes":"yes", "y":"yes", "ye":"yes", |
| 486 | "no":"no", "n":"no"} |
| 487 | if default == None: |
| 488 | prompt = " [y/n] " |
| 489 | elif default == "yes": |
| 490 | prompt = " [Y/n] " |
| 491 | elif default == "no": |
| 492 | prompt = " [y/N] " |
| 493 | else: |
| 494 | raise ValueError("invalid default answer: '%s'" % default) |
| 495 | |
| 496 | while 1: |
| 497 | sys.stdout.write(question + prompt) |
| 498 | choice = raw_input().lower() |
| 499 | if default is not None and choice == '': |
| 500 | return default |
| 501 | elif choice in valid.keys(): |
| 502 | return valid[choice] |
| 503 | else: |
| 504 | sys.stdout.write("Please respond with 'yes' or 'no' "\ |
| 505 | "(or 'y' or 'n').\n") |
| 506 | ## end of http://code.activestate.com/recipes/577058/ }}} |
| 507 | |
| 508 | def _capture_stdout(argv): |