2017-07-03 335 views
2

这个问题以前已经问过了,但是我已经试过相关问题的解决方案,如this无济于事。使用iPython/Spyder从Python退出的问题

我遇到了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

+0

我在Spyder中的IPython控制台内运行'exit'时看不到任何问题。它只是关闭当前的控制台(如预期的那样)。 'quit'和'Ctrl + D'也是一样。但是,'sys.exit()'显示您发布的消息。我认为它是由IPython人员引入的,以防止人们突然退出本次会议。我的版本:Spyder ** 3.1.4 **,IPython ** 5.3.0 **。 –

回答

1

我在运行包含Pycharm的IPython shell中的exit()脚本时遇到了同样的问题。 我学到了here,该退出针对交互式shell,因此行为将根据shell如何实现它而变化。

我能想出一个解决办法,...

  • 不杀退出内核
  • 没有显示追踪
  • 不会强迫你巩固与试/节选代码
  • 使用或不使用IPython,无需更改代码

只需将代码下面的“退出”导入到脚本中,您也可以使用int结束使用IPython运行并调用'exit()'应该可以工作。您也可以在jupyter中使用它(而不是quit,这是退出的另一个名称),它不像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