【发布时间】:2013-03-27 20:51:01
【问题描述】:
如何在我的代码中嵌入 IPython shell 并使其自动显示行号和调用它的函数?
我目前有以下设置可以在我的代码中嵌入 IPython shell:
from IPython.frontend.terminal.embed import InteractiveShellEmbed
from IPython.config.loader import Config
# Configure the prompt so that I know I am in a nested (embedded) shell
cfg = Config()
prompt_config = cfg.PromptManager
prompt_config.in_template = 'N.In <\\#>: '
prompt_config.in2_template = ' .\\D.: '
prompt_config.out_template = 'N.Out<\\#>: '
# Messages displayed when I drop into and exit the shell.
banner_msg = ("\n**Nested Interpreter:\n"
"Hit Ctrl-D to exit interpreter and continue program.\n"
"Note that if you use %kill_embedded, you can fully deactivate\n"
"This embedded instance so it will never turn on again")
exit_msg = '**Leaving Nested interpreter'
# Put ipshell() anywhere in your code where you want it to open.
ipshell = InteractiveShellEmbed(config=cfg, banner1=banner_msg, exit_msg=exit_msg)
这让我只需使用ipshell(),就可以在我的代码中的任何位置启动一个完整的 IPython shell。例如以下代码:
a = 2
b = a
ipshell()
在调用者范围内启动一个 IPython shell,允许我检查 a 和 b 的值。
我想做的是每当我调用ipshell()时自动运行以下代码:
frameinfo = getframeinfo(currentframe())
print 'Stopped at: ' + frameinfo.filename + ' ' + str(frameinfo.lineno)
这将始终显示 IPython shell 启动的上下文,以便我知道我正在调试什么文件/函数等。
也许我可以使用装饰器来做到这一点,但到目前为止我的所有尝试都失败了,因为我需要 ipshell() 在原始上下文中运行 (这样我就可以访问 a和来自 IPython shell 的 b)。
我怎样才能做到这一点?
【问题讨论】:
-
Ipython 并不是真正的调试器。为什么不使用 python 调试器?