Python tricks: “Press Enter to exit” on unhandled exception

When I write Python scripts on Windows, I often write a main() function, and when it throws an exception I don't handle, the console window closes immediately before giving me a chance to look at the traceback.

The bottom of main.py usually has these 2 lines, which call the main() function when the script is started by a double-click on the .py file:

if __name__ == '__main__':
    main()

Replace them with:

import sys, traceback
if __name__ == '__main__':
    try:
        main()
    except:
        traceback.print_exc()
        print >>sys.stderr
        print >>sys.stderr, "Press Enter to exit."
        blah = raw_input()

WordPress code-posting rant
In addition to what I wrote here, you should also replace any apostrophes with: '

5 Responses to “Python tricks: “Press Enter to exit” on unhandled exception”

  1. Kototama Says:

    Strange reflex : you don’t need the ‘blah’ variable at all ;-)

  2. yoni Says:

    That’s not quite true. There is a reason for it, and actually – you reminded me that I wanted to write a post about that.

  3. Python: Why to assign functions' return values to dummy variables « The Zero Flag Says:

    [...] Python: Why to assign functions’ return values to dummy variables In response to Kototama’s comment in the previous post: [...]

  4. Anonymous Says:

    אתה ישראלי ? :o

  5. yoni Says:

    hmm. Yes

Leave a Reply