[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

asynchronous alarm

Alan G Isaac

2/24/2008 7:07:00 AM

Goal: turn off an audible alarm without
terminating the program. For example,
suppose a console program is running::

while True:
sys.stdout.write('\a')
sys.stdout.flush()
time.sleep(0.5)

I want to add code to allow me to turn off
this alarm and then interact with the
program in its new state (which the alarm
alerts me to).

Question: how best to do this mostly simply
in a console application and in a Tkinter application?

I realize this must be a standard problem so that there
is a good standard answer. Here are some naive solutions
that occured to me.

Solution C1 (console): poll keyboard inside the loop.
E.g., <URL:http://effbot.org/librarybook/msvc...
Problem: no platform independent way to do this?

Solution C2 (console): handle KeyboardInterrupt.
An ugly hack. But works fine.

Solution C3 (console): start alarm in one thread
and wait for raw_input. (Should that be in another
thread? It does not seem to matter.)
This seems plausible, but I know nothing about threads
except that nonprogrammers tend to make mistakes
with them, so I hesitate.

Solution G1 (gui): start alarm in a thread but
include a test for a variable that can be set
by a button push? (Sounds plausible etc.)

Solution G2 (gui): start alarm but
somehow let Tkinter listen for an event
without programming any threads. Possible??

Thanks,
Alan
2 Answers

Paul Rubin

2/24/2008 7:19:00 AM

0

Alan Isaac <aisaac@american.edu> writes:
> while True:
> sys.stdout.write('\a')
> sys.stdout.flush()
> time.sleep(0.5)
>
> I want to add code to allow me to turn off this alarm and then
> interact with the program in its new state (which the alarm alerts
> me to).
>
> Question: how best to do this mostly simply in a console application
> and in a Tkinter application?

You'd usually use another thread to tell the loop when to exit,
or run the loop itself in another thread:

import sys,time
from threading import Event, Thread

def f(event):
while not event.isSet():
sys.stdout.write('\a')
sys.stdout.flush()
time.sleep(0.5)

a = Event()
Thread(target=f, args=(a,)).start()
raw_input('hit return when done: ')
a.set()

see the docs for the threading module, to make sense of this.

Alan G Isaac

2/24/2008 3:48:00 PM

0

Paul Rubin wrote:
> a = Event()
> Thread(target=f, args=(a,)).start()
> raw_input('hit return when done: ')
> a.set()

Simple and elegant.
Thank you.
Alan