我如何使python等待按下的键

我想我的脚本等待,直到用户按任何键。

我怎么做?

在Python 3中,不存在raw_input() 。 所以,只需使用:

 input("Press Enter to continue...") 

这只是等待用户按Enter键,所以你可能想要使用msvcrt ((仅限于Windows / DOS)msvcrt模块可以让你访问Microsoft Visual C / C ++运行时库(MSVCRT)中的许多函数):

 import msvcrt as m def wait(): m.getch() 

这应该等待一个关键的新闻。

在Python 2中执行此操作的一种方法是使用raw_input()

 raw_input("Press Enter to continue...") 

在python3它只是input()

在我的Linux机器上,我使用下面的代码。 这与其他地方提到的手动input类似,但是代码在一个紧密的循环中旋转,代码没有代码,并且有很多奇怪的代码没有考虑到这个代码。

 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 the character of the key that was pressed (zero 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 try: ret = sys.stdin.read(1) # returns a single character except KeyboardInterrupt: ret = 0 finally: # restore old state termios.tcsetattr(fd, termios.TCSAFLUSH, attrs_save) fcntl.fcntl(fd, fcntl.F_SETFL, flags_save) return ret 

如果您确定取决于系统命令,则可以使用以下命令:

Linux的:

 os.system('read -s -n 1 -p "Press any key to continue..."') print 

视窗:

 os.system("pause") 

简单使用

 input("Press Enter to continue...") 

会导致一个SyntaxError:分析时预期的EOF。

简单的修复使用:

 try: input("Press enter to continue") except SyntaxError: pass 

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) 

可以将其放入您的用例中。

我不知道一个独立于平台的方式,但是在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()返回按下的按键的序号,以使它具有相同的输出,我不得不施放它。

跨平台,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.getch() 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 / non-blocking的东西,因为它给了IOError ,我不需要它。 我正在使用此代码,因为我想要它阻止。 ;)

我是python的新手,我已经认为我太笨了,不能重现这里提出的最简单的build议。 事实certificate,有一个陷阱应该知道:

当一个python脚本从IDLE执行时,一些IO命令似乎performance完全不同(因为实际上没有terminal窗口)。

例如。 msvcrt.getch是非阻塞的,并且总是返回$ ff。 这已经被很久以前的报道(见例如https://bugs.python.org/issue9290 ) – 它被标记为固定的,不知何故这个问题似乎在当前版本的python / IDLE中持续存在。

所以,如果上面发布的任何代码不适合你,请尝试手动运行脚本,而不是从IDLE运行

如果你想看看他们是否按下了一个确切的关​​键(如说'B')做到这一点:

 while True: choice = raw_input("> ") if choice == 'b' : print "You win" input("yay") break 

os.system似乎总是调用sh,它不能识别s和n选项来读取。 然而,读命令可以传递给bash:

  os.system("""bash -c 'read -s -n 1 -p "Press any key to continue..."'""") 

或者你可以做

 print("This is a good joke") print("what happened when the chicken crossed the road") gap = input("") if gap == (""): print("") else: print("") print("it died")