Python - react to custom keyboard interrupt

最后都变了- 提交于 2019-12-12 03:49:36

问题


I am writing python chatbot that displays output through console. Every half second it asks server for updates, and responds to message. In the console I can see chat log.

This is sufficient in most cases, however, sometimes I want to interrupt normal workflow and write custom chat answer myself. I would love to be able to press a button (or combination) that would switch to "custom reply mode". What is the best way to do that, or achieve similar result?

Thanks a lot!


回答1:


Using select.select() on sys.stdin will allow you to check if a key has been pressed at the terminal.




回答2:


Given the comments in the previous answer, you need a non-blocking function to tell whether any keys were pressed rather than something that triggers as soon as the key was pressed.

I would therefore recommend using some of the terminal APIs available on your OS. Typically this would be curses or the win32 console API. However, I have written a common wrapper to both in asciimatics. The get_event() method on the Screen should provide a simple cross-platform way of getting mouse and keyboard events. To see if it was a keyboard event, check the type of returned event. If there was no event, you'll get a return code of None, but if it was a key pressed, you'll get KeyboardEvent.



来源:https://stackoverflow.com/questions/2882448/python-react-to-custom-keyboard-interrupt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!