我如何让我的python脚本等待,直到用户按下任何键?
当前回答
如果你想看看他们是否按了一个确切的键(比如“b”),可以这样做:
while True:
choice = raw_input("> ")
if choice == 'b' :
print "You win"
input("yay")
break
其他回答
操作系统。系统似乎总是调用sh,它不识别读取的s和n选项。但是read命令可以传递给bash:
os.system("""bash -c 'read -s -n 1 -p "Press any key to continue..."'""")
我是python的新手,我已经在想我太笨了,不能复制这里提出的最简单的建议。 事实证明,我们应该知道一个陷阱:
当从IDLE执行python脚本时,一些io命令的行为似乎完全不同(因为实际上没有终端窗口)。
如。msvcrt。Getch是非阻塞的,总是返回$ff。 这个问题很久以前就已经被报道过了(参见https://bugs.python.org/issue9290)——它被标记为已修复,不知怎么的,这个问题似乎在当前版本的python/IDLE中仍然存在。
因此,如果上面发布的任何代码对您不起作用,请尝试手动运行脚本,而不是从IDLE运行。
我不知道有什么平台独立的方法,但是在Windows下,如果你使用msvcrt模块,你可以使用它的getch函数:
import msvcrt
c = msvcrt.getch()
print 'you entered', c
MSCVCRT还包括非阻塞的kbhit()函数,以查看是否在没有等待的情况下按下了一个键(不确定是否有相应的curses函数)。在UNIX下,有一个curses包,但不确定是否可以使用它而不将其用于所有屏幕输出。这段代码在UNIX下工作:
import curses
stdscr = curses.initscr()
c = stdscr.getch()
print 'you entered', chr(c)
curses.endwin()
请注意,curses.getch()返回所按键的序号,以便使其具有与我强制转换时相同的输出。
如果你想看看他们是否按了一个确切的键(比如“b”),可以这样做:
while True:
choice = raw_input("> ")
if choice == 'b' :
print "You win"
input("yay")
break
在我的linux机器上,我使用以下代码。这类似于我在其他地方看到的代码(例如在旧的python faq中),但代码在一个紧密的循环中旋转,其中这段代码没有,并且有许多奇怪的角落情况,代码没有解释这段代码。
def read_single_keypress():
"""Waits for a single keypress on stdin.
This is a silly function to call if you need to do it a lot because it has
to store stdin's current setup, setup stdin for reading single keystrokes
then read the single keystroke then revert stdin back after reading the
keystroke.
Returns a tuple of characters of the key that was pressed - on Linux,
pressing keys like up arrow results in a sequence of characters. Returns
('\x03',) on KeyboardInterrupt which can happen when a signal gets
handled.
"""
import termios, fcntl, sys, os
fd = sys.stdin.fileno()
# save old state
flags_save = fcntl.fcntl(fd, fcntl.F_GETFL)
attrs_save = termios.tcgetattr(fd)
# make raw - the way to do this comes from the termios(3) man page.
attrs = list(attrs_save) # copy the stored version to update
# iflag
attrs[0] &= ~(termios.IGNBRK | termios.BRKINT | termios.PARMRK
| termios.ISTRIP | termios.INLCR | termios. IGNCR
| termios.ICRNL | termios.IXON )
# oflag
attrs[1] &= ~termios.OPOST
# cflag
attrs[2] &= ~(termios.CSIZE | termios. PARENB)
attrs[2] |= termios.CS8
# lflag
attrs[3] &= ~(termios.ECHONL | termios.ECHO | termios.ICANON
| termios.ISIG | termios.IEXTEN)
termios.tcsetattr(fd, termios.TCSANOW, attrs)
# turn off non-blocking
fcntl.fcntl(fd, fcntl.F_SETFL, flags_save & ~os.O_NONBLOCK)
# read a single keystroke
ret = []
try:
ret.append(sys.stdin.read(1)) # returns a single character
fcntl.fcntl(fd, fcntl.F_SETFL, flags_save | os.O_NONBLOCK)
c = sys.stdin.read(1) # returns a single character
while len(c) > 0:
ret.append(c)
c = sys.stdin.read(1)
except KeyboardInterrupt:
ret.append('\x03')
finally:
# restore old state
termios.tcsetattr(fd, termios.TCSAFLUSH, attrs_save)
fcntl.fcntl(fd, fcntl.F_SETFL, flags_save)
return tuple(ret)
推荐文章
- 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中重置生成器对象