Re: asynchronous alarm

2008-02-24 Thread Alan Isaac
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
-- 
http://mail.python.org/mailman/listinfo/python-list


asynchronous alarm

2008-02-23 Thread 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
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: asynchronous alarm

2008-02-23 Thread Paul Rubin
Alan Isaac [EMAIL PROTECTED] 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.
-- 
http://mail.python.org/mailman/listinfo/python-list