asynchronous alarm

A

Alan Isaac

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/msvcrt.htm>
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
 
P

Paul Rubin

Alan Isaac said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top