Using threads to quit the main python process

James Mills prologic at
Wed Oct 29 02:11:02 CET 2008

On Wed, Oct 29, 2008 at 10:42 AM, sharpblade <sharpblade1 at> wrote:
> Is there a way I can use threads to quit the main python process?
> In brief, I have a python script that starts when my computer starts. It
> chooses a random wallpaper background out of a specified path, and sets it
> as the desktop wallpaper. It also hooks some windows hot keys so I can cycle
> through all the wallpapers, or choose another one, or quit it, by using F8,
> F7 and F6 respectively.
> However, I would quite like the script to self-terminate if no user input is
> received after X seconds. At first this seemed simple - Create a separate
> thread that used time.sleep() to sleep for X seconds, then run a callback.
> The callback would check a simple Boolean (Set to True if a hot key is
> pressed, set to False at start of the script), and if the Boolean was False,
> it would simply run exit(), and this would close the window.
> However, it is not that simple. The callback and the thread work fine, but
> the exit() seems to close the THREAD, not the main process. I have tried
> sys.exit(), and some other forms I found on the Internet (Raising exceptions
> and setting the thread to a daemon), but none seemed to close the actual
> interpreter. I tried using the .join() function, but this called an
> exception that told me the thread could not be joined.
> Here is my code:

I prefer not to use threads if I can help it. Here's
a simple little example that doesn't use threads
at all and uses an event-driven approach instead
using my circuits library [1].
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: set sw=3 sts=3 ts=3

from circuits import listener, Event, Component, Timer, Manager
from import Stdin

class Test(Component):

  def onSTOP(self):
     raise SystemExit, 0

  def onINPUT(self, data):
     print data

def main():
  manager = Manager()
  stdin = Stdin()
  test = Test()
  timer = Timer(5, Event(), "stop")

  manager += stdin
  manager += test
  manager += timer

  while True:
     except SystemExit:
     except KeyboardInterrupt:

if __name__ == "__main__":



-- "Problems are solved by method"

More information about the Python-list mailing list