How do I make python to wait for a pressed key

2019-01-01 06:41发布

I want my script to wait until the user presses any key.

How do I do that?

12条回答
妖精总统
2楼-- · 2019-01-01 07:04

If you want to see if they pressed a exact key (like say 'b') Do this:

while True:
    choice = raw_input("> ")

    if choice == 'b' :
        print "You win"
        input("yay")
        break
查看更多
墨雨无痕
3楼-- · 2019-01-01 07:05

Cross Platform, Python 2/3 code:

# 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

I removed the fctl/non-blocking stuff because it was giving IOErrors and I didn't need it. I'm using this code specifically because I want it to block. ;)

查看更多
像晚风撩人
4楼-- · 2019-01-01 07:06

One way to do this in Python 2, is to use raw_input():

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

In python3 it's just input()

查看更多
浅入江南
5楼-- · 2019-01-01 07:09

In Python 3, no raw_input() exists. So, just use:

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

This only waits for a user to press enter though, so you might want to use msvcrt ((Windows/DOS only) The msvcrt module gives you access to a number of functions in the Microsoft Visual C/C++ Runtime Library (MSVCRT)):

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

This should wait for a key press.

查看更多
其实,你不懂
6楼-- · 2019-01-01 07:09

If you are ok with depending on system commands you can use the following:

Linux:

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

Windows:

os.system("pause")
查看更多
素衣白纱
7楼-- · 2019-01-01 07:09

If you want to wait for enter (so the user knocking the keyboard does not cause something un-intended to happen) use

sys.stdin.readline()
查看更多
登录 后发表回答