def cleanup():
    ... clean up script ...

# on exit
atexit.register(cleanup)