我如何让我的python脚本等待,直到用户按下任何键?
当前回答
你可以使用键盘库:
import keyboard
keyboard.wait('space')
print('space was pressed, continuing...')
其他回答
操作系统。系统似乎总是调用sh,它不识别读取的s和n选项。但是read命令可以传递给bash:
os.system("""bash -c 'read -s -n 1 -p "Press any key to continue..."'""")
你可以使用键盘库:
import keyboard
keyboard.wait('space')
print('space was pressed, continuing...')
在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)
它可以滚动到您的用例中。
如果你想看看他们是否按了一个确切的键(比如“b”),可以这样做:
while True:
choice = raw_input("> ")
if choice == 'b' :
print "You win"
input("yay")
break
推荐文章
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象