按esc键停止,并按其他任何键继续在Python中 [英] Press esc to stop and any other key to continue in Python

查看:1416
本文介绍了按esc键停止,并按其他任何键继续在Python中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Now with help of raw_input, I can call a method every time user presses Enter.

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

有一个问题,因为只有Ctrl + C,该程序才能停止.如您所见,我使程序等待用户按下键.

There is a problem because only Ctrl + C, the program can be stopped. As you see, I make my program to wait user to press key.

opencv中,我发现有类似的需求.

From opencv, I find there is a similar need.

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

我只想按Esc键退出程序,然后按其他任何键继续.所以有什么办法可以做到这一点?

Simply I want to press esc key to exit program and press any other key to continue. So there is any way to do like this?

我的操作系统是OSX.

My os is OSX.

推荐答案

您可以使用pynput,它更易于使用.

you can use pynput,it's easier to use.

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()

这篇关于按esc键停止,并按其他任何键继续在Python中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆