raw_input in python without pressing enter

后端 未结 8 1583
情歌与酒
情歌与酒 2020-11-22 15:41

I\'m using raw_input in Python to interact with user in shell.

c = raw_input(\'Press s or n to continue:\')
if c.upper() == \'S\':
    print \'Y         


        
8条回答
  •  爱一瞬间的悲伤
    2020-11-22 15:59

    On a side note, msvcrt.kbhit() returns a boolean value determining if any key on the keyboard is currently being pressed.

    So if you're making a game or something and want keypresses to do things but not halt the game entirely, you can use kbhit() inside an if statement to make sure that the key is only retrieved if the user actually wants to do something.

    An example in Python 3:

    # this would be in some kind of check_input function
    if msvcrt.kbhit():
        key = msvcrt.getch().decode("utf-8").lower() # getch() returns bytes data that we need to decode in order to read properly. i also forced lowercase which is optional but recommended
        if key == "w": # here 'w' is used as an example
            # do stuff
        elif key == "a":
            # do other stuff
        elif key == "j":
            # you get the point
    

提交回复
热议问题