Windows/DOS: double clicking a .py file

Chris Gonnerman chris.gonnerman at newcenturycomputers.net
Wed Sep 11 08:48:49 EDT 2002


----- Original Message ----- 
From: "Just" <just at xs4all.nl>


> Sorry if this is a Windows FAQ, I'm a newbie to Windows, but not to 
> Python.
> 
> If I double-click a Python script (or use the start command in the dos 
> prompt) a new dos prompt window is opened and my program is run. The 
> window goes away when the program is done. However, the window _also_ 
> goes away when the program raises an exception, making it virtually 
> impossible to actually _see_ the exception... Is there a way to keep the 
> dos prompt window in this case?

import sys, traceback

try:
    do_something_here()

except:
    # show the error
    traceback.print_exc(file=sys.stderr)
    # save the error
    try:
        import time
        fp = open("my_error_log.txt", "a")
        fp.write("\n%s\n" % time.ctime(time.time())
        traceback.print_exc(file=fp)
        fp.close()
    except:
        pass
    # email the error
    try:
        import smtplib, StringIO
        fp = StringIO.StringIO()
        traceback.print_exc(file=fp)
        conn = smtplib.SMTP("my.email.server.com")
        conn.sendmail("me at my.email.server.com", 
            [ "me at my.email.server.com" ], fp.getvalue())
        conn.quit()
        fp.close()
    except:
        pass
    # hold the screen
    sys.stderr.write("\nPress ENTER to Continue: ")
    sys.stdin.readline()

A couple of notes:

I import traceback at the very top, to prevent any possibility
that it can't be imported later.

I don't import smtplib or time at the top (unless I need them
anyway) since I won't (hopefully) need them all the time.

You mustn't screw with sys.stdin or sys.stderr if you expect 
this to work (yes, you could use msvcrt.getch() on Windows,
which is where you said you are, but I like cross-platform
code).

Code above is untested, but I use similar code in many of my
programs; any error is most likely a typo.

Standard disclaimers apply.

Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net
http://newcenturycomputers.net





More information about the Python-list mailing list