如何将IPython Interpreter嵌入到在IPython Qt控制台中运行的应用程序中

Ero*_*mic 12 ipython python-2.7 qtconsole

关于这一点有一些主题,但没有一个有令人满意的答案.

我有一个在IPython qt控制台中运行的python应用程序

http://ipython.org/ipython-doc/dev/interactive/qtconsole.html

当我遇到错误时,我希望能够在那时与代码进行交互.

    try: 
      raise Exception()
    except Exception as e:
        try: # use exception trick to pick up the current frame
            raise None
        except:
            frame = sys.exc_info()[2].tb_frame.f_back
        namespace = frame.f_globals.copy()
        namespace.update(frame.f_locals)
        import IPython
        IPython.embed_kernel(local_ns=namespace)  
Run Code Online (Sandbox Code Playgroud)

我认为这会奏效,但我收到一个错误:

RuntimeError:线程只能启动一次

sim*_*mon 47

我只是用这个:

from IPython import embed; embed()
Run Code Online (Sandbox Code Playgroud)

对我来说比其他任何东西都更好:)


Ame*_*ina 5

您可以按照以下方法将 IPython 会话嵌入到您的程序中:

try:
    get_ipython
except NameError:
    banner=exit_msg=''
else:
    banner = '*** Nested interpreter ***'
    exit_msg = '*** Back in main IPython ***'

# First import the embed function
from IPython.frontend.terminal.embed import InteractiveShellEmbed
# Now create the IPython shell instance. Put ipshell() anywhere in your code
# where you want it to open.
ipshell = InteractiveShellEmbed(banner1=banner, exit_msg=exit_msg)
Run Code Online (Sandbox Code Playgroud)

然后ipshell()在您想放入 IPython shell 时使用。这将允许您在代码中嵌入(甚至嵌套)IPython 解释器并检查对象或程序状态。