我如何让我的python脚本等待,直到用户按下任何键?


当前回答

在Python 3中,使用input():

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

在Python 2中,使用raw_input():

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

其他回答

在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'

我不知道有什么平台独立的方法,但是在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

操作系统。系统似乎总是调用sh,它不识别读取的s和n选项。但是read命令可以传递给bash:

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