我如何在Python中"点击任何键"(或获取菜单选项)?
有没有一种可移植的方法来使用标准库?
Joh*_*kin 34
try:
    # Win32
    from msvcrt import getch
except ImportError:
    # UNIX
    def getch():
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old = termios.tcgetattr(fd)
        try:
            tty.setraw(fd)
            return sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old)
try:
  os.system('pause')  #windows, doesn't require enter
except whatever_it_is:
  os.system('read -p "Press any key to continue"') #linux
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", `c`
        except IOError: pass
finally:
    termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
    fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
但是,这仅适用于Unix变体。我认为没有跨平台的方式。
几年前,我编写了一个小型库来以跨平台的方式执行此操作(直接受到上面 John Millikin 回答的启发)。此外getch,它还带有一个pause打印功能'Press any key to continue . . .':
pause()
您也可以提供自定义消息:
pause('Hit any key')
如果下一步是退出,它还附带了一个调用的便利函数sys.exit(status):
pause_exit(status=0, message='Hit any key')
安装pip install py-getch,或在此处查看。