[Tutor] scripts close window when finished

Daniel Yoo dyoo@hkn.EECS.Berkeley.EDU
Fri, 4 Aug 2000 01:51:17 -0700 (PDT)


On Thu, 3 Aug 2000, Brett wrote:

> 	I'm new to python and just started making some simple scripts.  I use 
> windows98, and when I run stuff i coded in python a dos window opens and 
> and program goes by too fast for me to read the output.  One solution i 
> found was ending them with a 'Z = input('end') line, but this only works 
> when the script gets to the end, and doesnt let me see where a buggy script 
> crashed.  What can I do?

This is where the 'try/except' exception handling stuff comes handy.  
When an exception occurs as a result of an error, it usually causes the
system to die with an error message.  However, if you've wrapped the
offending code with a try/except, you can override the default 'print
error and die' behavior:

###
try:
    # some code here that might cause problems or bugginess
    print 5/0

except:
    raw_input("Please press enter to continue...")
###

Here, I'm just getting it to pause if anything bad happens.  Also, since
we're just using raw_input/input, we can ignore the return value.

Unfortunately, the above doesn't specifically report the exception that
occurred.  Usually, we'd like more detailed information.  To do this, we
can use the 'traceback' module, which provides good debugging info:

###
try:
    print 5/0
    # or other code that you're writing
except:
    import traceback, sys
    sys.stderr.write('Error while executing program %s.' % sys.argv[0])
    traceback.print_exc(file=sys.stderr)
    raw_input("Please press enter to continue: ")
###


I pillaged the above code from a CGI-tutorial at:

  http://www.webtechniques.com/archives/1998/02/kuchling/

These error-handling issues occur during CGI programming too, so it's good
that you're learning about this.  More information on exception handling
and that traceback module can be found on these urls:

Tutorial section on exception handling:
  http://www.python.org/doc/current/tut/node10.html

Library reference on the 'traceback' module:
  http://www.python.org/doc/current/lib/module-traceback.html

Good luck!