我是python的新手,我有一个python2.x脚本,它要求用户在bash中输入答案A、B或C。在等待用户输入时,如果只按了退出键,如何使脚本立即退出?
现在,我有这个函数。但是,在退出键之后,我也必须按enter键。
def choice(prompt):
"""
Choose A, B or C
ESC exits script
"""
while True:
char = raw_input(prompt)
if char.encode() == '\x1B': # ESC is pressed
sys.exit("Quitting ...")
elif char.lower() not in ('a', 'b', 'c'):
print("Wrong input. Please try again.")
continue
else:
break
return char
user_choice = choice("\nChoose between A - C: ")
print("You chose %s.") % user_choice.upper()
代码是UTF-8格式的,bash终端中的退出键给了我^[。据我所知,msvcrt不能在Linux上运行。可以做到这一点吗?这样脚本就可以在Windows和Linux中工作了?
发布于 2015-04-20 14:32:24
要在用户不必按enter键的情况下读取和输入,您可以使用msvcrt
模块。你可以在here上找到更多关于它的信息。
https://stackoverflow.com/questions/29740566
复制相似问题