flixic
flixic

Reputation: 43

Python - react to custom keyboard interrupt

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!

Upvotes: 0

Views: 1887

Answers (2)

Peter Brittain
Peter Brittain

Reputation: 13619

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.

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

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

Upvotes: 1

Related Questions