我如何让我的python脚本等待,直到用户按下任何键?
当前回答
如果你想看看他们是否按了一个确切的键(比如“b”),可以这样做:
while True:
choice = raw_input("> ")
if choice == 'b' :
print "You win"
input("yay")
break
其他回答
在Python 3中,使用input():
input("Press Enter to continue...")
在Python 2中,使用raw_input():
raw_input("Press Enter to continue...")
跨平台,Python 2/3代码:
# import sys, os
def wait_key():
''' Wait for a key press on the console and return it. '''
result = None
if os.name == 'nt':
import msvcrt
result = msvcrt.getwch()
else:
import termios
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)
try:
result = sys.stdin.read(1)
except IOError:
pass
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
return result
我删除了fctl/非阻塞的东西,因为它给IOErrors,我不需要它。我使用这段代码是因为我想让它阻塞。;)
附录:
我在PyPI上的一个包中实现了这个功能,还有很多其他叫做console的东西:
>>> from console.utils import wait_key
>>> wait_key()
'h'
操作系统。系统似乎总是调用sh,它不识别读取的s和n选项。但是read命令可以传递给bash:
os.system("""bash -c 'read -s -n 1 -p "Press any key to continue..."'""")
在Python 3中,使用input():
input("Press Enter to continue...")
在Python 2中,使用raw_input():
raw_input("Press Enter to continue...")
不过,这只需要等待用户按下enter键。
在Windows/DOS上,可能需要使用msvcrt。msvcrt模块允许你访问Microsoft Visual C/ c++运行时库(msvcrt)中的一些函数:
import msvcrt as m
def wait():
m.getch()
这应该等待一个按键。
注:
在python3中,raw_input()不存在。 在Python 2中,input(prompt)等价于eval(raw_input(prompt))。
python手册提供了以下内容:
import termios, fcntl, sys, os
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)
oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
try:
while 1:
try:
c = sys.stdin.read(1)
print "Got character", repr(c)
except IOError: pass
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
它可以滚动到您的用例中。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录