【问题标题】:Executing Python via Jupyter: Calling quit() and exit() raises NameError通过 Jupyter 执行 Python:调用 quit() 和 exit() 引发 NameError
【发布时间】:2020-09-04 18:46:47
【问题描述】:

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

test.py

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

myFunc()

test.ipynb

#executes test.py
%run test.py

【问题讨论】:

    标签: python jupyter-notebook nameerror


    【解决方案1】:

    那是因为你在两个不同的 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()
    

    哪个做同样的事情:)

    【讨论】:

    • 如果我直接执行文件,print(sys.executable) 返回的结果与通过 jupyter 运行相同:/Applications/anaconda3/bin/python
    • 如果您在答案中添加sys.exit() 来替代quit(),我很乐意接受它,因为它解决了我的问题。从你的链接中得到的;)
    猜你喜欢
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 2013-03-30
    • 2017-04-28
    • 1970-01-01
    相关资源
    最近更新 更多