2017-07-03 336 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