代码之家  ›  专栏  ›  技术社区  ›  Somebody still uses you MS-DOS

python中未按enter键的原始输入

  •  20
  • Somebody still uses you MS-DOS  · 技术社区  · 16 年前

    raw_input 在Python中与shell中的用户交互。

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

    它按预期工作,但用户必须在按“s”后在shell中按enter。有没有一种方法可以在不需要在shell中按enter键的情况下从用户输入中完成我需要的内容?我用的是数码机。

    6 回复  |  直到 16 年前
        1
  •  23
  •   Alex Martelli    16 年前

    在窗户下,你需要 msvcrt 具体来说,从你描述问题的方式,功能 msvcrt.getch

    读取按键并返回 结果字符。什么都没有回音 到控制台。此呼叫将阻止 如果还没有按键 可用,但不等待输入 被压迫。

    this recipe 一个简单的方法来建立一个类似的 getch

        2
  •  15
  •   systempuntoout    16 年前

    Python不提供现成的多平台解决方案。
    如果你在窗户上,你可以试试 msvcrt 使用:

    import msvcrt
    print 'Press s or n to continue:\n'
    input_char = msvcrt.getch()
    if input_char.upper() == 'S': 
       print 'YES'
    
        3
  •  7
  •   Adrian Rosoga    6 年前

    实际上在这段时间里(从这个线程开始的将近10年),一个名为 pynput 出现。 在第一个切口下方-即仅适用于小写's'。 我已经在Windows上测试过它,但我几乎100%肯定它应该在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")
    
        4
  •  6
  •   Community Mohan Dere    6 年前

    诅咒也可以做到这一点:

    import curses, time
    
    def input_char(message):
        try:
            win = curses.initscr()
            win.addstr(0, 0, message)
            while True: 
                ch = win.getch()
                if ch in range(32, 127): 
                    break
                time.sleep(0.05)
        finally:
            curses.endwin()
        return chr(ch)
    
    c = input_char('Do you want to continue? y/[n]')
    if c.lower() in ['y', 'yes']:
        print('yes')
    else:
        print('no (got {})'.format(c))
    
        5
  •  4
  •   Derek Kurth    10 年前

    为了得到一个字符,我使用了 getch ,但我不知道它是否在Windows上工作。

        6
  •  3
  •   John Howard    16 年前

    而不是 msvcrt WConio :

    >>> import WConio
    >>> ans = WConio.getkey()
    >>> ans
    'y'
    
        7
  •  1
  •   Nytra    10 年前

    另一方面,msvcrt.kbhit文件()返回一个布尔值,确定当前是否正在按键盘上的任何键。

    因此,如果您正在制作一个游戏或其他东西,并且希望按键可以执行某些操作,但不能完全停止游戏,那么可以在if语句中使用kbhit(),以确保只有在用户确实想要执行某些操作时才检索到该键。

    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
    
        8
  •  1
  •   Meir Gabay    7 年前

    我需要解决这个问题 和 不安装任何外部Python包 .

    我的解决方案,以防其他人看到这个帖子

    https://github.com/unfor19/mg-tools/blob/master/mgtools/get_key_pressed.py

    from tkinter import Tk, Frame
    
    
    def __set_key(e, root):
        """
        e - event with attribute 'char', the released key
        """
        global key_pressed
        if e.char:
            key_pressed = e.char
            root.destroy()
    
    
    def get_key(msg="Press any key ...", time_to_sleep=3):
        """
        msg - set to empty string if you don't want to print anything
        time_to_sleep - default 3 seconds
        """
        global key_pressed
        if msg:
            print(msg)
        key_pressed = None
        root = Tk()
        root.overrideredirect(True)
        frame = Frame(root, width=0, height=0)
        frame.bind("<KeyRelease>", lambda f: __set_key(f, root))
        frame.pack()
        root.focus_set()
        frame.focus_set()
        frame.focus_force()  # doesn't work in a while loop without it
        root.after(time_to_sleep * 1000, func=root.destroy)
        root.mainloop()
        root = None  # just in case
        return key_pressed
    
    
    def __main():
            c = None
            while not c:
                    c = get_key("Choose your weapon ... ", 2)
            print(c)
    
    if __name__ == "__main__":
        __main()
    
        9
  •  0
  •   sudormrfbin    5 年前

    如果你能使用外部库, blessed (跨平台)很容易做到:

    from blessed import Terminal
    
    term = Terminal()
    
    with term.cbreak(): # set keys to be read immediately 
        print("Press any key to continue")
        inp = term.inkey() # wait and read one character
    

    with 将禁用终端的块、行编辑功能。

    文件 cbreak , inkey ,和 example 具有 .