2013-03-01 72 views
5

有幾個話題,但沒有一個答案滿意。如何將IPython解釋器嵌入在IPython Qt控制檯中運行的應用程序

我在IPython的QT控制檯

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

運行的Python應用程序。當我遇到一個錯誤,我希望能夠與在該點的代碼交互。

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:線程只能啓動一次

回答

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) 

然後使用ipshell(),只要你想被放入IPython shell。這將允許您在代碼中嵌入(甚至嵌套)IPython解釋器,並檢查對象或程序的狀態。

23

我只是用這個:

from IPython import embed; embed() 

工作比什麼都好,我:)

+0

我喜歡用這個去探索新的項目。我創建了一個bit.ly URL j.mp/ipshell,可以將其捲入到我的代碼中。它指向https://gist.github.com/RichardBronosky/570492 – 2016-11-21 15:07:29

相關問題