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

时间:2013-03-01 21:30:53

标签: python-2.7 ipython 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)  

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

RuntimeError:线程只能启动一次

2 个答案:

答案 0 :(得分:42)

我只是用这个:

from IPython import embed; embed()

对我来说比其他任何事情都更好:)

答案 1 :(得分:4)

您可以按照the following recipe将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)

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