cleanup actions on sys.exit()

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Jindra
    New Member
    • Apr 2012
    • 4

    cleanup actions on sys.exit()

    Hello,
    I wrote a GUI app in Jython (using Java Swing) which uses database. The application remains connected for its whole run time until the main window is closed (JFrame, using defaultCloseOpe ration = JFrame.EXIT_ON_ CLOSE).
    Now, when exiting, I would like to make sure I explicitly close the database connection. Is there any function, like _atexit() in C, where I could place my code?
    Thank you very much.
  • dwblas
    Recognized Expert Contributor
    • May 2008
    • 626

    #2
    I use the __del__ function however because of the way the Python garbage collector uses a count of references, you may have to be explicit on closing some objects, like file pointers.

    Comment

    • Jindra
      New Member
      • Apr 2012
      • 4

      #3
      Oh, yes, this is what I was looking for but could not find! :) Thank you, dwblas!
      Strangely, I haven't heard of __del__ since I first learn some python (version 1.6, I guess).
      In the meantime, I found there is one more way in Swing, and that is Runtime.addShut downHook(Thread ).
      I defined this function:
      Code:
      class ShutdownTask( java.lang.Thread ):
          def __init__( self, connection ):
              self.conn = connection
              print 'ShutdownTask setup: object = %s' % connection
          def run( self ):
              print 'ShutdownTask in progress'
              if self.conn is not None:
                  try:
                      print 'ShutdownTask: shutting down database connection'
                      self.conn.conn.close()
                      print 'ShutdownTask: connection closed'
                  except Exception, e:
                      print 'ShutdownTask: exception'
                      print e
              print 'ShutdownTask: done'
      and in the init thread I call this:
      Code:
          Q = Connection() # my class to represent database connection
          shutdownTask = ShutdownTask( Q )
          java.lang.Runtime.getRuntime().addShutdownHook( shutdownTask )
      Works perfectly and is "Swing native", but __del__ in the main GUI class should do the same job.

      Comment

      Working...