tags:

views:

365

answers:

3

I have a python cgi script that accepts user uploads (via sys.stdin.read). After receiving the file (whether successfully or unsuccessfully), the script needs to do some cleanup. This works fine when upload finishes correctly, however if the user closes the client, the cgi script is silently killed on the server, and as a result no cleanup code gets executed. How can i force the script to always finish.

+1  A: 

You can trap the exit signal with the signal module. Haven't tried this with mod_python though.

http://docs.python.org/library/signal.html

Note in the docs:

When a signal arrives during an I/O operation, it is possible that the I/O operation raises an exception after the signal handler returns. This is dependent on the underlying Unix system’s semantics regarding interrupted system calls.

You may need to catch I/O exceptions for the broken pipe and/or file write if you don't sys.exit from your handler.

SpliFF
mod_python wouldn't be involved here, if the OP is running the script as a CGI script.
David Zaslavsky
+1  A: 

The script is probably not killed silently; you just don't see the exception which python throws. I suggest to wrap the whole script in try-except and write any exception to a log file.

This way, you can see what really happens. The logging module is your friend.

Aaron Digulla
When the client closes -- and the socket eventually times out -- you should get an I/O error of some kind.
S.Lott
A: 

You may be able to use the atexit module.

http://docs.python.org/library/atexit.html

From the documentation:

The atexit module defines a single function to register cleanup functions. Functions thus registered are automatically executed upon normal interpreter termination.

Note: the functions registered via this module are not called when the program is killed by a signal, when a Python fatal internal error is detected, or when os._exit() is called.

This is an alternate interface to the functionality provided by the sys.exitfunc variable.

monkut