如何等待按键?

798 投票
13 回答
1413674 浏览
提问于 2025-04-15 12:11

我该如何让我的Python脚本等到用户按下任意键后再继续运行呢?

13 个回答

62

在我的Linux电脑上,我使用了以下代码。这段代码和我在其他地方看到的代码很像(比如以前的Python常见问题解答),但那段代码会一直不停地循环,而这段代码不会。此外,那段代码没有考虑到很多奇怪的边界情况,而这段代码则考虑到了这些情况。

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)
342

在Python 3中,使用 input() 来获取用户输入:

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

在Python 2中,使用 raw_input() 来获取用户输入:

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

Python 3中,使用input()来获取用户输入:

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

而在Python 2中,使用raw_input()

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

不过,这个方法只会等用户按下回车键。


在Windows或DOS系统中,你可能想用msvcrt模块。这个msvcrt模块可以让你使用一些微软Visual C/C++运行库中的功能:

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

这个方法应该可以等待用户按下任意键。


注意:

在Python 3中,raw_input()这个函数是不存在的。
在Python 2中,input(prompt)的功能相当于eval(raw_input(prompt))

撰写回答