正如您提到的,最简单的方法是使用
raw_input()(或仅
input()对于Python
3)。没有内置的方法可以做到这一点。从577058号配方中:
import sysdef query_yes_no(question, default="yes"): """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 <Enter>. It must be "yes" (the default), "no" or None (meaning an answer is required of the user). The "answer" return value is True for "yes" or False for "no". """ valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} if default is None: prompt = " [y/n] " elif default == "yes": prompt = " [Y/n] " elif default == "no": prompt = " [y/N] " else: raise ValueError("invalid default answer: '%s'" % default) while True: sys.stdout.write(question + prompt) choice = raw_input().lower() if default is not None and choice == '': return valid[default] elif choice in valid: return valid[choice] else: sys.stdout.write("Please respond with 'yes' or 'no' " "(or 'y' or 'n').n")
用法示例:
>>> query_yes_no("Is cabbage yummier than cauliflower?")Is cabbage yummier than cauliflower? [Y/n] oopsPlease respond with 'yes' or 'no' (or 'y' or 'n').Is cabbage yummier than cauliflower? [Y/n] [ENTER]>>> True>>> query_yes_no("Is cabbage yummier than cauliflower?", None)Is cabbage yummier than cauliflower? [y/n] [ENTER]Please respond with 'yes' or 'no' (or 'y' or 'n').Is cabbage yummier than cauliflower? [y/n] y>>> True
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)