Python JupyterLab: Stop the execution of a code at a line

Viewed 1427

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?

5 Answers

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!")
Related