I like to paste hunks of code into an ipython window during development and debug. I also have a situation where I want to stop execution if a condition happens:
if condition:
<stop running>
Solutions like sys.exit() appear to exit all the way out of ipython back to a terminal prompt. Is there another way? At the moment I do this:
if condition:
fjklsd;
Which gives an error and returns to the ipython prompt, but is pretty ugly too.
You can raise this exception raise KeyboardInterrupt
Related
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.
I have a long code that sometimes I do not want to execute all of the code, but just stop at a certain line. To stop the execution of a code at a line, I do the following:
print('Stop here: Print this line')
quit()
print('This line should not print because the code should have stopped')
The right answer is only the first line should print. When I use quit(), quit , exit(), or exit both lines print. When I use import sys and then sys.exit() I get the following error message
An exception has occurred, use %tb to see the full traceback.
SystemExit
C:\Users\user\anaconda3\lib\site-packages\IPython\core\interactiveshell.py:3351:
UserWarning: To exit: use 'exit', 'quit', or Ctrl-D. warn("To exit:
use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
How can I perform this task of stopping execution at a line?
In case you are trying to debug the code and may want to resume from where it stopped, you should be using pdb instead
print('Stop here: Print this line')
import pdb; pdb.set_trace()
print('This line should not print because the code should have stopped')
When you execute it, the interpreter will break at that set_trace() line. You will then be prompted with pdb prompt. You can check the values of variable at this prompt. To continue execution press c or q to quit the execution further. Check other useful command of pdb.
It appears that you would like to stop the code at a certain point of your choosing
To do this I found two possible ways within your constraints.
One is that you simply write
raise Exception("Finished code")
This would allow you to stop the code and raise your own exception and write whatever exception you so choose.
However, if you would like to not have any exception whatsoever then I would point you to this link: https://stackoverflow.com/a/56953105/14727419.
It seems to be an issue related to iPython, as seen here.
If you don't wish to use the solution provided there, and don't mind forcefully killing the process, you can do:
import os
os.system('taskkill /F /PID %d' % os.getpid())
For your debugging purposes it fine to use the builtin debugger pdb. The following link gives a tutorial how to set it up: Debug Jupyter
This is what I have to prevent unintentional execution of the Tests section at the bottom of the pipeline:
import pdb
# this line should capture the input, temporarily
# preventing subsequent notebook cells from being executed
pdb.set_trace()
# this line causes pdb to exit with an error, which is required
# to stop subsequent cells from execution if user fails to type
# "exit" in pdb command line and just presses the Stop button in the Notebook interface
raise Error("This line should fail to prevent cells below from being executed regardless of how pdb was exited!")
This question may have been asked a couple of times but I cannot seem to find it.
Basically I am just learning Python and I am on Windows, this means I double click the .py file and open it. This works great until an error appears, at which point Python calls exit and the window closes.
One way, of course, to get around this is to use the cmd program in Windows and run the Python program from there, however, is there a way to fix it so that my application doesn't bail out and close as soon as it hits an error if I open it from Windows Explorer?
while(True):
try:
number = input('Enter a number: ')
if(is_int(number) is False):
print('Please actually enter a number')
if(number > 0):
answer = input('Oh Noes you really want that?')
if(answer == 'yes'):
sys.exit(0);
except KeyboardInterrupt:
sys.exit(0)
except Exception as e:
input('')
In order to keep your program intact, e.g. to not introduce unwanted catch-em-all exception handling (aka pokemon handling) there are at least three options:
Use any console terminal, e.g. built-in cmd or powershell or any third-party console apps out there.
Use any IDE: pycharm, IDLE (python windows installer by default sets it up) or whatever you have capable of running python code.
Use text editor plugins for running python code. At least notepad++ and sublime text are capable of doing so.
I would recommend starting with option 1 for starters, then slowly move to option 3 for small scripts and projects, and option two for larger ones.
I you put an input function at the bottom of your script then it will hang there until you hit enter or close the command prompt. If you call an exit function put it immediately before the exit function is called. Otherwise place it at the bottom of the script.
Also I assume you have defined is_int already in your script?
What would you think it should do?
Python is drawing the window you see, if python crashes, the windows is going away.
You can run it trough cmd, or within an IDE. (like IDLE, that has some problem though when it comes to GUI)
Otherwise, add something like this at the end of the file
try:
run()
except Exception as inst:
print type(inst), inst.args
#it prints the exception
print sys.exc_traceback.tb_lineno
#if you want the line number where the error occurred in the source code
raw_input()
inst is the exception instance, you can see the type and the list of arguments.
Then with the sys module you can also see the line where the error occurred in the code.
This way every error will be handled and displayed before closing
Is this the right way?
No. You should really be using ad IDE (like Eclipse with PyDev or PyCharm).
After #SeçkinSavaşçı's extremely useful comment at the start:
The most common way is to let it wait for an input, then ignore the input and terminate the script.
Which took me a second to understand I went in search of how to do this, so first I saw to stop the script and used:
while(True):
try:
# Application code here
except:
input('')
Which worked really well to catch all errors, which unlike in PHP (which I have become comfortable with unfortunately) are all exceptions.
So the next part was to to tell me what error had occured and how to fix it, I needed a backtrace. It just so happens that the Python docs gave me the answer right here: http://docs.python.org/2/library/traceback.html#traceback-examples in an easy to see example:
exc_type, exc_value, exc_traceback = sys.exc_info()
print(traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout));
Add that above the input('') and I had my perfect error handling showing me everything I needed.
Thanks all,
Try import time and time.sleep(). Also, I recommend you to use IDLE or Geany. I've been using them and they work out well.
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...')
After opening an interactive console while debugging using
code.interact(local=locals())
How can I resume code execution. I have checked the docs for the 'code' module and search stack overflow but cannot find anything.
It's the same way you exit any Python interpreter session: send an end-of-file character.
That's Ctrl-D on Linux or Ctrl-Z Enter on Windows.
If like me you always forget to hit Ctrl-D, you can wrap up your prompt in a try/except block:
try:
code.interact(local=locals())
except SystemExit:
pass