tags:

views:

53

answers:

2

I'm looking at writing a portable, light-weight Python app. As the "GUI toolkit" I'm most familiar with — by a wide margin! — is HTML/CSS/JS, I thought to use Django as a framework for the project, using its built-in "development server" (manage.py runserver).

I've been banging on a proof-of-concept for a couple hours and the only real problem I've encountered so far is shutting down the server once the user has finished using the app. Ideally, I'd like there to be a link on the app's pages which shuts down the server and closes the page, but nothing I see in the Django docs suggests this is possible.

Can this be done? For that matter, is this a reasonable approach for writing a small, portable GUI tool?

+2  A: 

One brute force approach would be to let the process kill itself, like:

# somewhere in a views.py

def shutdown(request):
    import os
    os.kill(os.getpid(), 9) 

Note: os.kill is only available on Unix (Windows alternative may be something like this: http://metazin.wordpress.com/2008/08/09/how-to-kill-a-process-in-windows-using-python/)

The MYYN
Unfortunately, I need to support Windows users, as well. :-)
Ben Blank
http://metazin.wordpress.com/2008/08/09/how-to-kill-a-process-in-windows-using-python/
The MYYN
Hey, that just might work. I'll leave the question open for a bit to see if I can catch a more subtle, Django-friendly method than "shoot it in the face", but it does seem to get the job done. ;-)
Ben Blank
... 9? You don't think that `atexit` handlers should get called?
Ignacio Vazquez-Abrams
Yes, they should. But by default, there are no `atexit` handlers registered in django. Anything I am missing?
The MYYN
Not that I can tell. Accepted, and thanks for the help!
Ben Blank
+1  A: 

Take a look at the source code for python manage.py runserver:

http://code.djangoproject.com/browser/django/trunk/django/core/management/commands/runserver.py

When you hit Ctrl+C, all it does is call sys.exit(0), so you could probably just do the same.

Edit: Based on your comment, it seems Django is catching SystemExit when it calls your view function. Did you try calling sys.exit in another thread?

import threading
thread = threading.Thread(target=sys.exit, args=(0,))
thread.start()

Edit: Nevermind, sys.exit from another thread only terminates that thread, which is not well documented in the Python docs. =(

FogleBird
That was my first thought, but Django catches the `SystemExit` exception and returns it as a page! :-D
Ben Blank
@Ben Blank: See my edit.
FogleBird