关于这个问题,有几个话题,但都没有满意的答案。
我有一个在IPython qt控制台中运行的Python应用程序。
http:/ipython.orgipython-docdevinteractiveqtconsole.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: Threads can only be started once(线程只能启动一次)
我就用这个。
from IPython import embed; embed()
对我来说比其他任何东西都好用 :)
更新。
为了庆祝这个答案获得50个赞,以下是我在这段代码发布后的6年里所做的更新。
首先,我现在喜欢在一条语句中导入和执行,就像我使用的 黑色 我现在所有的python代码都是用这个方法来编写的,而且在这个特殊的、不寻常的上下文中,它对原始代码段进行了重新格式化。 所以。
__import__("IPython").embed()
考虑到我经常在循环或线程中使用这个代码,包含一个允许终止父进程的代码段可能会很有帮助 (部分是为了方便,部分是为了提醒自己最好的方法)。 os._exit
在这里,终止父进程是最好的选择,所以我的代码段包含了这个(与使用单个语句的逻辑相同)。
q = __import__("functools").partial(__import__("os")._exit, 0)
然后我可以简单地使用 q()
ifwhen我想退出主进程。
我的完整代码段(有 # FIXME
以防我有可能忘记删除它!)看起来像这样。
q = __import__("functools").partial(__import__("os")._exit, 0) # FIXME
__import__("IPython").embed() # FIXME
你可以按照 下面的食谱 将一个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解释器。这将允许你在你的代码中嵌入(甚至是嵌套)IPython解释器,并检查对象或程序的状态。