How to do “hit any key” in python?

后端 未结 7 1779
予麋鹿
予麋鹿 2020-12-01 09:00

How would I do a \"hit any key\" (or grab a menu option) in Python?

  • raw_input requires you hit return.
  • Windows msvcrt has getch() and getche().
  • <
相关标签:
7条回答
  • 2020-12-01 09:39

    on linux platform, I use os.system to call /sbin/getkey command, e.g.

    continue_ = os.system('/sbin/getkey -m "Please any key within %d seconds to continue..." -c  10')
    if continue_:
       ...
    else:
       ...
    

    The benefit is it will show an countdown seconds to user, very interesting :)

    0 讨论(0)
  • 2020-12-01 09:40

    From the python docs:

    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)
    

    This only works for Unix variants though. I don't think there is a cross-platform way.

    0 讨论(0)
  • 2020-12-01 09:44

    I implemented it like the following in Windows. getch() takes a one single character

    import msvcrt
    char = 0
    print 'Press any key to continue'
    while not char:
        char = msvcrt.getch()
    
    0 讨论(0)
  • 2020-12-01 09:47
    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)
    
    0 讨论(0)
  • 2020-12-01 09:47
    try:
      os.system('pause')  #windows, doesn't require enter
    except whatever_it_is:
      os.system('read -p "Press any key to continue"') #linux
    
    0 讨论(0)
  • 2020-12-01 09:50

    A couple years ago I wrote a small library to do this in a cross-platform way (inspired directly by John Millikin's answer above). In addition to getch, it comes with a pause function that prints 'Press any key to continue . . .':

    pause()
    

    You can provide a custom message too:

    pause('Hit any key')
    

    If the next step is to exit, it also comes with a convenience function that calls sys.exit(status):

    pause_exit(status=0, message='Hit any key')
    

    Install with pip install py-getch, or check it out here.

    0 讨论(0)
提交回复
热议问题