如何解决通过Jupyter执行Python:调用quit和exit引发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()
做同样的事情:)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。