raw_input in python without pressing enter

后端 未结 8 1499
情歌与酒
情歌与酒 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:58

    To get a single character, I have used getch, but I don't know if it works on Windows.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-22 16:05

    Under Windows, you need the msvcrt module, specifically, it seems from the way you describe your problem, the function msvcrt.getch:

    Read a keypress and return the resulting character. Nothing is echoed to the console. This call will block if a keypress is not already available, but will not wait for Enter to be pressed.

    (etc -- see the docs I just pointed to). For Unix, see e.g. this recipe for a simple way to build a similar getch function (see also several alternatives &c in the comment thread of that recipe).

    0 讨论(0)
  • 2020-11-22 16:05

    Actually in the meantime (almost 10 years from the start of this thread) a cross-platform module named pynput appeared. Below a first cut - i.e. that works with lowercase 's' only. I have tested it on Windows but I am almost 100% positive that it should work on Linux.

    from pynput import keyboard
    
    print('Press s or n to continue:')
    
    with keyboard.Events() as events:
        # Block for as much as possible
        event = events.get(1e6)
        if event.key == keyboard.KeyCode.from_char('s'):
            print("YES")
    
    0 讨论(0)
  • 2020-11-22 16:06

    Python does not provide a multiplatform solution out of the box.
    If you are on Windows you could try msvcrt with:

    import msvcrt
    print 'Press s or n to continue:\n'
    input_char = msvcrt.getch()
    if input_char.upper() == 'S': 
       print 'YES'
    
    0 讨论(0)
  • 2020-11-22 16:14

    Instead of the msvcrt module you could also use WConio:

    >>> import WConio
    >>> ans = WConio.getkey()
    >>> ans
    'y'
    
    0 讨论(0)
提交回复
热议问题