By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,825 Members | 970 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,825 IT Pros & Developers. It's quick & easy.

cleanup actions on sys.exit()

P: 4
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 defaultCloseOperation = 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.
Apr 16 '12 #1

✓ answered by dwblas

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.
http://eli.thegreenplace.net/2009/06...ors-in-python/

Share this Question
Share on Google+
2 Replies

Expert 100+
P: 626
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.
http://eli.thegreenplace.net/2009/06...ors-in-python/
Apr 18 '12 #2

P: 4
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.addShutdownHook(Thread).
I defined this function:
Expand|Select|Wrap|Line Numbers
  1. class ShutdownTask( java.lang.Thread ):
  2.     def __init__( self, connection ):
  3.         self.conn = connection
  4.         print 'ShutdownTask setup: object = %s' % connection
  5.     def run( self ):
  6.         print 'ShutdownTask in progress'
  7.         if self.conn is not None:
  8.             try:
  9.                 print 'ShutdownTask: shutting down database connection'
  10.                 self.conn.conn.close()
  11.                 print 'ShutdownTask: connection closed'
  12.             except Exception, e:
  13.                 print 'ShutdownTask: exception'
  14.                 print e
  15.         print 'ShutdownTask: done'
  16.  
and in the init thread I call this:
Expand|Select|Wrap|Line Numbers
  1.     Q = Connection() # my class to represent database connection
  2.     shutdownTask = ShutdownTask( Q )
  3.     java.lang.Runtime.getRuntime().addShutdownHook( shutdownTask )
  4.  
Works perfectly and is "Swing native", but __del__ in the main GUI class should do the same job.
Apr 18 '12 #3

Post your reply

Sign in to post your reply or Sign up for a free account.