1
votes

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?

4
Am I right assuming you are doing this for the sake of debugging?MaKaNu
Have you tried raising an exception? You can add something like raise ValueError which will throw an exception.Matt C
@MaMaNu: Yes for debugging mostly, but also sometimes I just want to execute the code up to a point.ASE
@Matt C: How to do this? When I added raise ValueError I got an error --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-4-cf8caaab243c> in <module>ASE
sys.exit(0) is the right way to exit normally from a program. Exit code 0 tells the system, that there was no error. If IPython sees this as a problem and posts a warning, then it's a IPython "problem"user8408080

4 Answers

2
votes

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.

1
votes

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.

0
votes

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())
0
votes

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