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

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')

try:
execfile('1.py')
except SystemExit:
print "1.py exited"
Exit is an exception which can be caught.

Related

how do I prevent python exe from closing when an error occurs

try:
some code here
except Exception as e:
print("error: ",e)
here if this python exe code produces an exception it immediately closes the exe terminal
how do I stop it from exiting the exe terminal so that I can understand what exception exactly occurred
also I cant run it in CMD I have to run the exe file only
also I cant use the press any key method
The terminal closes when the program terminates. When you catch the exception, you print your error message, and then the program terminate, so you don't really gain much from catching the exception; in fact, you even get less (you don't print the stack trace).
To get the stacktrace, look into traceback:
try:
foo = 123 / 0
except Exception as e:
traceback.print_exception(e)
Then you need to have the program wait a bit that you can actually see the stack trace and error you print. A simple way is to just wait for input:
try:
foo = 123 / 0
except Exception as e:
traceback.print_exception(e)
wait_for_it = input('Press enter to close the terminal window')
Or you could add a break point to have the Python debugger pdb come up. (It does at least on Mac OS when I run this code in a terminal, no idea about Windows.) See the above link for help on it, or type help at its prompt.
try:
foo = 123 / 0
except Exception as e:
breakpoint()
Speaking of terminal: if you just open a command prompt or bash terminal, you can just run your code with python3 myprog.py and that terminal does not automatically close, so that you can see the output without modifying the program. Depending on how you run your code and what module dependencies you have, this may need a bit more setup (like a virtual environment) but is probably worth it in the long run.

Is an exception thrown when I'm stopping the program?

I'm writing some program in python, and whenever I stop the program deliberatly (from the stop button in the PyCharm client) I want the program to execute some more commands before stopping. Is an exception thrown when I stop the program? I tried to add a try except with KeyboardInterrupt exception but it didn't work.
You can catch KeyboardInterrupt errors.
Try to run this script and kill it and you will see that KeyboardInterrupt happened! will be printed:
import time
try:
time.sleep(5)
except KeyboardInterrupt:
print("KeyboardInterrupt happened!")
raise

Terminate Blender with Exit Code "1" when run from command line

I am working with an automated Blender python script and I would like to know how to terminate it with an Exit Code 1 when an Exception occurs.
The problem seems to be that the exit code from blender is always 0 even if the python script fails.
The following script definately produces a non-zero exit code, but blender sets exit code to 0
def main():
raise Exception("Fail")
sys.exit(1)
I also tried the --python-exit-code command line argument but to no effect:
C:\blender.exe --python-exit-code 2 --disable-abort-handler -P bake.py
this gives a slightly better result, because I get the following message:
Error: script failed, file: 'bake.py', exiting with code 2.
Unfortunately the exit code is still 0.
Can anyone enlighten me with some explanations or solutions on how I can exit the process with the correct exit code?
Thanks a lot for any hints!
--python-exit-code as stated in the documentation sets the exit code if the command line script called with --python raises an exception, not when it exits with a non-zero code.
Set the exit-code in [0..255] to exit if a Python exception is raised (only for scripts executed from the command line), zero disables.
Thus the only solution is to do your checking, and raise an exception manually, then catch it and exit in the except block. (If you don't exit right away, the exit code reverts to 0.
This code worked for me when doing unit tests inside a blender addon.
import unittest
from tests.my_test import MyTest
import sys
def run():
suite = unittest.defaultTestLoader.loadTestsFromTestCase(MyTest)
success = unittest.TextTestRunner().run(suite).wasSuccessful()
if not success:
raise Exception('Tests Failed')
try:
run()
except Exception:
sys.exit(1)

How to stay in the cmd window when the exception has been raised?

I have written a programme by python which is successfully tested under eclipse.Then I used pyinstaller to excute it as a .exe file. When the programme raise the exception ,the cmd window will quit immediately. I want to stay in this window to take a good look at this exception. How can I do it ? Thank you.
As Ms Turdy mentioned, you should run it in a command prompt or terminal first, if it will have the same behavior as the exe.
You can execute a python script with python -m pdb script.py and it will enter into the debugger. You run it by pressing C for continue, then it will break when it raises the exception.
That is because the python script has finished its job. You can do this:
import time
# your code
...
time.sleep(20)
This will give you 20 seconds to see the result. And after 20 s, the cmd window will remain 20 s for you to see the result. You can change the time for your requirement.
You can try raw_input to hold the screen:
import traceback
try:
# do something dangerous
except Exception, e:
print 'Error:', e
print traceback.format_exc()
raw_input('Input anything to end...')

How can I have a python script safely exit itself?

Heres the scenario I have a password that must be entered if entered wrong the script will not proceed and just exit itself? But how can I tell the script to safely exit itself?
I tried sys.exit() but that gives a traceback error and doesn't seem like a very clean exit method.
In fact, sys.exit() will only throw a SystemExit exception, which would make the program exit if this exception wasn't catched, but I don't think it's poor coding.
Anyway, another possibility is to use os._exit(0) if you need to exit immediately at any cost. (cf. http://docs.python.org/2/library/exceptions.html#exceptions.SystemExit)
you are using the sys module, but you haven't imported it.
add this before the sys.exit() line :
import sys

Categories