【问题标题】:Press esc to stop and any other key to continue in Python在 Python 中按 esc 停止并按任何其他键继续
【发布时间】:2018-07-25 01:09:39
【问题描述】:

现在在raw_input 的帮助下,我可以在用户每次按下Enter 时调用一个方法。

if __name__ == '__main__':
    while True:
        raw_input("Press Enter to continue...")
        _start()
def _start():
     print("HelloWorld")

有一个问题,因为只有Ctrl + C,程序可以停止。如您所见,我让我的程序等待用户按键。

来自opencv,我发现有类似的需求。

# Hit 'q' on the keyboard to quit!
if cv2.waitKey(1) & 0xFF == ord('q'):
    break

我只想按 esc 键退出程序并按任何其他键继续。那么有没有办法做到这一点呢?

此外

我的操作系统是 OSX。

【问题讨论】:

    标签: python keyboard


    【解决方案1】:

    您最好的选择可能是采用curses 方式。

    import curses
    
    def main():
        stdscr = curses.initscr()
        while True:
            key = stdscr.getch()
            if key == 27: # This is the escape key code
                 curses.endwin()
                 break
    
    main()
    

    【讨论】:

    • 输出很奇怪。
    • 你能再具体一点吗?除了你按下的键之外应该没有输出
    • 是的,我按ESC 后,输出消失了。但是程序运行的时候,我按了其他任意键,输出的格式很奇怪。
    • 我在 OS X 和 iTerm2 上试过这个,你用的是不同的终端吗?
    • 你添加_start()方法了吗?
    【解决方案2】:

    你可以使用pynput,它更容易使用。

    from pynput import keyboard
    
    def _start():
         print("HelloWorld")
    def on_press(key):
        if key == keyboard.Key.esc:
            # Stop listener
            return False
        else:
            _start()
    
    # Collect events until released
    with keyboard.Listener(
            on_press=on_press) as listener:
        listener.join()
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-10
    • 2015-01-23
    • 2020-03-14
    • 2020-06-02
    • 1970-01-01
    • 2011-12-13
    • 2020-08-10
    • 1970-01-01
    相关资源
    最近更新 更多