问题
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