gpt4 book ai didi

ipython - 使用 iPython/Spyder 从 Python 退出的问题

转载 作者:行者123 更新时间:2023-12-01 11:20:06 38 4
gpt4 key购买 nike

这个问题之前也有人问过,但我尝试过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

最佳答案

我在 Pycharm 的 IPython shell 中运行包含 exit() 的脚本时遇到了同样的问题。
学到了here ,该导出旨在用于交互式 shell ,因此行为将根据 shell 如何实现它而有所不同。

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

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

  • 只需将下面代码中的“exit”导入到您还打算使用 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

    关于ipython - 使用 iPython/Spyder 从 Python 退出的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44893461/

    38 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com