【问题标题】:problems exiting from Python using iPython/Spyder使用 iPython/Spyder 从 Python 退出的问题
【发布时间】:2017-12-07 04:30:59
【问题描述】:

这个问题之前有人问过,但是我试过this等相关问题中的解决方法都无济于事。

我在使用 Python 的 exit 命令时遇到问题,并且我已经排除了我的代码由 vanilla Python 3 运行的问题。当我使用 iPython 或在 Spyder 的 iPython 控制台中运行它时,问题就出现了。

当我只使用一个简单的退出命令时,我得到了错误:

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)

我只说这种“有效”是因为错误消息更小,所以不那么烦人:)。

有什么想法吗?似乎是 iPython 的问题。我在 Jupyter(使用 iPython)中遇到了一个不同的问题,其中完全忽略了退出,我单独发布了 here

【问题讨论】:

  • 在 Spyder 的 IPython 控制台中运行 exit 时,我没有发现任何问题。它只是关闭当前控制台(如预期的那样)。 quitCtrl+D 也是如此。但是,sys.exit() 显示您发布的消息。我认为它是由 IPython 人员引入的,以防止人们突然退出当前会话。我的版本:Spyder 3.1.4、IPython 5.3.0.
  • 我知道我的回答来晚了,你的情况不是这样吗?

标签: ipython spyder


【解决方案1】:

我在 Pycharm 的 IPython shell 中运行包含 exit() 的脚本时遇到了同样的问题。 我了解到here,exit 是为交互式 shell 设计的,所以行为会根据 shell 的实现方式而有所不同。

我可以想出一个解决方案...

  • 退出时不杀死内核
  • 不显示回溯
  • 不要强迫您使用 try/excepts 来巩固代码
  • 使用或不使用 IPython,无需更改代码

只需将下面代码中的“exit”导入您也打算使用 IPython 运行的脚本中,然后调用“exit()”就可以了。你也可以在 jupyter 中使用它(而不是 quit,这只是 exit 的另一个名称),它不会像在 IPython shell 中那样安静地退出,让你知道......

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

【讨论】:

    【解决方案2】:

    您可以使用系统警告将不需要的警告设置为忽略。例子: 您从其他地方调用的函数:

    def my_function:
      statements
    
                        
        if (something happened that you want to exit):
            
            import warnings
            warnings.filterwarnings("ignore")
            sys.exit('exiting...')
    
    

    【讨论】:

      猜你喜欢
      • 2020-12-01
      • 2014-01-04
      • 2015-07-30
      • 2019-04-27
      • 1970-01-01
      • 2020-05-16
      • 2018-01-05
      • 2018-04-15
      • 1970-01-01
      相关资源
      最近更新 更多