Search code examples
pythonjupyter-notebooknameerror

Executing Python via Jupyter: Calling quit() and exit() raises NameError


I'm executing a Python file text.py via Jupyter. I didn't get that error so far, but something changed, and now calling quit() or exit() raises a NameError. What causes this problem now?

test.py

def myFunc():
    print('yes')
    quit()

myFunc()

test.ipynb

#executes test.py
%run test.py

Solution

  • That's because you are running python on two different python environment.

    To check which env you are running you can add this two lines on top of your code:

    import sys
    print(sys.executable)
    
    def myFunc():
        print('yes')
        quit()
    
    myFunc()
    

    running with:

    python3 test.py 
    

    leads to this output

    /usr/bin/python3
    yes
    

    instead from jupyter I obtain this:

    /snap/jupyter/6/bin/python
    yes
    
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    /home/marco/Documents/gibberish/test.py in <module>
          6     quit()
          7 
    ----> 8 myFunc()
          9 
         10 
    
    /home/marco/Documents/gibberish/test.py in myFunc()
          4 def myFunc():
          5     print('yes')
    ----> 6     quit()
          7 
          8 myFunc()
    
    NameError: name 'quit' is not defined
    

    Basically when you are running the code from jupyter you are loading a different set of builtin libraries

    Anyway quit should be used only from the interpreter

    Or you can simply use

    sys.exit()
    

    Which does the same thing :)