以前有人问过这个问题,但我在这类相关问题上尝试过解决办法,但都无济于事。

我在使用python的exit命令时遇到了问题,并且排除了使用普通python 3运行的代码的问题。当我使用ipython或Spyder的ipython控制台运行它时,问题就出现了。

当我只使用一个简单的exit命令时,我会得到错误:

NameError: name 'exit' is not defined

我已经按照另一个链接的建议导入了sys。唯一有效的方法是尝试sys.exit(),在这种情况下我得到:

An exception has occurred, use %tb to see the full traceback.

SystemExit

C:\Users\sdewey\AppData\Local\Continuum\Anaconda3\lib\site-

packages\IPython\core\interactiveshell.py:2870: UserWarning: To exit: use

'exit', 'quit', or Ctrl-D.

warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)

我只说"有点效果",因为错误消息较小,所以不那么烦人。

有什么想法吗?似乎是伊普生的问题。我在Jupyter(使用ipython)遇到了另一个问题,完全忽略了戒烟,我在这里单独发布了这个问题。

在Spyder的ipython控制台中运行exit时,我没有看到任何问题。它只是关闭当前控制台(如预期)。同样适用于quit和Ctrl+D。但是,sys.exit()显示了您发布的消息。我认为这是由ipython的人介绍的,以防止人们突然退出当前的会话。我的版本:Spyder 3.1.4,IPython 5.3.0。

我知道我的回答迟了,对你来说不管用吗?

在pycharm的ipython shell中运行包含exit()的脚本时,我遇到了同样的问题。我在这里了解到,出口是为交互式shell设计的,因此行为将根据shell实现它的方式而变化。

我可以想出一个解决办法…

退出时不杀死内核

不显示回溯

不强制您使用try/exceptions来巩固代码

使用或不使用ipython,不更改代码

只需将下面的代码中的"exit"导入到您还打算用ipython运行的脚本中,调用"exit()"就可以了。你也可以在jupyter中使用它(而不是quit,这只是出口的另一个名字),在那里,它不会像ipython外壳那样安静地出口,让你知道…

An exception has occurred, use %tb to see the full traceback.

IpyExit

"""

# ipython_exit.py

Allows exit() to work if script is invoked with IPython without

raising NameError Exception. Keeps kernel alive.

Use: import variable 'exit' in target script with 'from ipython_exit import exit'

"""

import sys

from io import StringIO

from IPython import get_ipython

class IpyExit(SystemExit):

"""Exit Exception for IPython.

Exception temporarily redirects stderr to buffer.

"""

def __init__(self):

# print("exiting")  # optionally print some message to stdout, too

# ... or do other stuff before exit

sys.stderr = StringIO()

def __del__(self):

sys.stderr.close()

sys.stderr = sys.__stderr__  # restore from backup

def ipy_exit():

raise IpyExit

if get_ipython():    # ...run with IPython

exit = ipy_exit  # rebind to custom exit

else:

exit = exit      # just make exit importable

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐