pythonexecfile

how to exit python execfile() with out exiting whole script


I have a code which runs mutile python codes such as below:

execfile("1.py")
execfile("2.py")
execfile("3.py")

however occasionally one of the above codes as an error, i put exit('error') in the code to cancell if there is an error. However i want the rest of the code to run and exit('error') exits the whole code, not just the execfile. How do i get the execfile to stop but the others to keep running?

The part of 1.py with exit() is:

try :
    Ntot=10000
    x,y,s=myMCMC2D(Ntot,0.78,0.63,1,1)
except :
    exit('error')

Solution

  • try:
        execfile('1.py')
    except SystemExit:
        print "1.py exited"
    

    Exit is an exception which can be caught.