Using threads to quit the main python process

James Mills prologic at shortcircuit.net.au
Wed Oct 29 02:11:02 CET 2008


On Wed, Oct 29, 2008 at 10:42 AM, sharpblade <sharpblade1 at gmail.com> 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 threaded_test.py code: http://pastebin.com/f6060d15a

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].
<code>
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: set sw=3 sts=3 ts=3

from circuits import listener, Event, Component, Timer, Manager
from circuits.lib.io import Stdin

class Test(Component):

  @listener("stop")
  def onSTOP(self):
     raise SystemExit, 0

  @listener("stdin:read")
  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:
     try:
        manager.flush()
        stdin.poll()
        timer.poll()
     except SystemExit:
        break
     except KeyboardInterrupt:
        break

if __name__ == "__main__":
  main()
</code>

cheers
James

[1] http://hg.softcircuit.com.au/projects/circuits/
http://trac.softcircuit.com.au/circuits/

--
--
-- "Problems are solved by method"



More information about the Python-list mailing list