[Tutor] Console Application - Key Events

Alan Gauld alan.gauld at btinternet.com
Tue May 8 09:59:40 CEST 2012

On 08/05/12 02:44, BRAGA, Bruno wrote:
> I would like to know if there is any "easy" way to handle events (such
> as mouse movements, keyboard keys pressed, etc) in console based python
> applications?

You need to be more specific about what you mean.
Consoles don't have mice. Keyboard events are easily
handled (see my tutorial on event driven apps for
more info and examples)

You may be confusing the concept of a console running
inside a window of a GUI system. In that case the
window receives events and the window manager can
handle them. But the python application running
inside that terminal emulator is completely unaware
of them.

There are also event driven frameworks for consoles
that can capture events (Borland had one such for DOS),
but it is the framework not Python that is aware of
these things.

> More specifically, I am working on a screensaver for terminals
> (http://termsaver.info), so I would like to simulate the same behaviour
> of a standard screensaver for the X windows, by:

What is this screensaver going to do? Display an alternative
screen full of text? Go blank?

>   * running on background
>   * starting some functionality (display a text, etc) if there is no
>     event (mouse or keyboard) for more than N minutes
>   * stopping the above if there is any movement detected

It is possible to do some of that in a multi process environment
by running an application in the background, but you would need some 
kind of cooperative behaviour from the foreground app I suspect.
Which limits applicability.

But the biggest problem you face is just that consoles generally
do not have any kind of event awareness. Mice etc just don't exist.
They are not event based. And where the terminal emulator is
event aware (eg xterm on Linux) the events are not passed on
to the app except in very limited circumstances - eg pasting
from a mouse selection - and that is usually just a case of
injecting the selected text into stdin. And that is deliberate since the 
apps need to be able to work in real dumb terminals (VT100 etc)
or even teletypes.

Alan G
Author of the Learn to Program web site

More information about the Tutor mailing list