0

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
maxischl
  • 579
  • 1
  • 11
  • 29

1 Answers1

1

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

Nikaido
  • 4,443
  • 5
  • 30
  • 47
  • If I execute the file directly, `print(sys.executable)` returns the same as running via jupyter: `/Applications/anaconda3/bin/python` – maxischl Sep 04 '20 at 19:20
  • 1
    If you add `sys.exit()` as replacement for `quit()`to your answer, I'm happy to accept it, since it solves my problem. Got that from your link ;) – maxischl Sep 04 '20 at 19:24