通过 Jupyter 执行 Python:调用 quit() 和 exit() 引发 NameError

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

我正在通过 Jupyter 执行 Python 文件 text.py。到目前为止我没有收到那个错误,但是有些事情发生了变化,现在调用 quit()exit() 会引发 NameError。现在是什么原因导致这个问题?

test.py

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

myFunc()

test.ipynb

#executes test.py
%run test.py

那是因为你 运行 python 在两个不同的 python 环境中。

要检查你是哪个环境 运行 你可以在你的代码之上添加这两行:

import sys
print(sys.executable)

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

myFunc()

运行:

python3 test.py 

导致此输出

/usr/bin/python3
yes

我从 jupyter 获得了这个:

/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

基本上,当你是 运行 来自 jupyter 的代码时,你正在加载一组不同的内置库

Anyway quit should be used only from the interpreter

或者您可以简单地使用

sys.exit()

哪个做同样的事情:)