[Tutor] Listen for input while performing other tasks

Steven D'Aprano steve at pearwood.info
Sun Nov 25 13:03:08 CET 2012


On 25/11/12 22:06, Sean Carolan wrote:
> I'm working on a python script that runs on a Raspberry Pi.  The script
> detects when hardware buttons are pressed, and then runs functions based on
> that input.
>
> I want to be able to always listen for a button press, no matter what the
> script is doing at the current moment.  When a button press is detected,
> the script should stop whatever it is doing, and move to the next "mode" or
> function.
>
> So far I've only been able to come up with kludgy implementations with lots
> of short time.sleep() calls alternating with checks to see whether the
> buttons were pressed or not.
>
> There has to be a cleaner way to do this.

Not really. Running code in parallel (the bit of your script doing the work,
and the bit of the script listening for a button press) is inherently icky.
Even when it is easy, it is only easy because of an incredible amount of
work happening in the background hiding the complexity.



> Do you have any ideas how to make this work?


(1) Use some sort of framework (e.g. a GUI application framework) with a
proper event loop. This is likely the only good solution. Tkinter may do
do the job. So might pyev:

http://code.google.com/p/pyev/

assuming you can get libev running on a Raspberry Pi.


(2) Write your own event loop, which will probably need to be in C and
will probably be horrible to write and horrible to use. Wait, it may
not be that horrible, because you're only interested in reading from
the keyboard, which you may be able to do using non-blocking reads.

Let me think about this one...


(4) Possibly using threads or processes.


(5) Since you're probably using Linux on your Raspberry Pi, you can use
the signal module to listen for specific signals rather than any arbitrary
key press. That might be close enough to solve your problem.


Explaining exactly what you are hoping to do might simplify the issue
somewhat.



-- 
Steven


More information about the Tutor mailing list