threading.Thread vs. signal.signal

Discussion in 'Python' started by Jack Orenstein, Sep 18, 2005.

  1. I'd like to create a program that invokes a function once a second,
    and terminates when the user types ctrl-c. So I created a signal
    handler, created a threading.Thread which does the invocation every
    second, and started the thread. The signal handler seems to be
    ineffective. Any idea what I'm doing wrong? This is on Fedora FC4 and
    Python 2.4.1. The code appears below.

    If I do the while ... sleep in the main thread, then the signal
    handler works as expected. (This isn't really a satisfactory
    implementation because the function called every second might
    take a significant fraction of a second to execute.)

    Jack Orenstein


    import sys
    import signal
    import threading
    import datetime
    import time

    class metronome(threading.Thread):
    def __init__(self, interval, function):
    threading.Thread.__init__(self)
    self.interval = interval
    self.function = function
    self.done = False

    def cancel(self):
    print '>>> cancel'
    self.done = True

    def run(self):
    while not self.done:
    time.sleep(self.interval)
    if self.done:
    print '>>> break!'
    break
    else:
    self.function()

    def ctrl_c_handler(signal, frame):
    print '>>> ctrl c'
    global t
    t.cancel()
    sys.stdout.close()
    sys.stderr.close()
    sys.exit(0)

    signal.signal(signal.SIGINT, ctrl_c_handler)

    def hello():
    print datetime.datetime.now()

    t = metronome(1, hello)
    t.start()
     
    Jack Orenstein, Sep 18, 2005
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jerry Sievers

    thread, threading; how to kill a thread?

    Jerry Sievers, Nov 17, 2004, in forum: Python
    Replies:
    12
    Views:
    1,186
    Mustafa Demirhan
    Nov 19, 2004
  2. Replies:
    9
    Views:
    1,127
    Mark Space
    Dec 29, 2007
  3. ~levon

    signal and threading

    ~levon, Aug 25, 2008, in forum: Python
    Replies:
    1
    Views:
    244
    ~levon
    Aug 25, 2008
  4. Steven Woody
    Replies:
    0
    Views:
    476
    Steven Woody
    Jan 9, 2009
  5. Steven Woody
    Replies:
    0
    Views:
    490
    Steven Woody
    Jan 9, 2009
Loading...

Share This Page