errors using python.exe

591
5
Jump to solution
04-25-2014 01:15 PM
AmyKlug
Occasional Contributor III
If I run my python code using a text file via python.exe from windows desktop (open with) or task scheduler, is there a way to see if there were any errors? would a try/except work?
Tags (2)
0 Kudos
1 Solution

Accepted Solutions
MattEiben
Occasional Contributor
Yep, just use "finally" as part of your try/except/finally block.  The finally code executes no matter what after your code goes through the try/except.

import traceback  try:     Your Code Here  except:     traceback.print_exc()  finally:     raw_input("Press any key to close this window")

View solution in original post

0 Kudos
5 Replies
MattEiben
Occasional Contributor
A try/except block would do this.
Maybe something along these lines.

import traceback

try:
    Your Code Here

except:
    outfile = open("error.txt","w")
    outfile.write(traceback.format_exc())
    outfile.close()
0 Kudos
AmyKlug
Occasional Contributor III
A try/except block would do this.
Maybe something along these lines.

import traceback

try:
    Your Code Here

except:
    outfile = open("error.txt","w")
    outfile.write(traceback.format_exc())
    outfile.close()


Thanks that worked!!!!!!

now.......

Do you know of a way to add the error as a message to the python.exe window the code is running and have the window stay open instead of closing? the same as if you run a tool that errors in arcmap and you do NOT check "close this dialog when completed successfully"?
0 Kudos
MattEiben
Occasional Contributor
Yep, just use "finally" as part of your try/except/finally block.  The finally code executes no matter what after your code goes through the try/except.

import traceback  try:     Your Code Here  except:     traceback.print_exc()  finally:     raw_input("Press any key to close this window")
0 Kudos
AmyKlug
Occasional Contributor III
That is so cool! thanks!
0 Kudos
AmyKlug
Occasional Contributor III
I just tested this on code with no errors. how can I get the python window only stay open when there are errors?


EDIT: I figured it out

Box stays open with and without errors:


except:
    traceback.print_exc()
    raw_input("ERRORS OCCURRED")

finally:
    raw_input("Update Successful")


Box closes if no errors:

except:
    traceback.print_exc()
    raw_input("ERRORS OCCURRED")
0 Kudos