【问题标题】:Using IPython as an effective debugger使用 IPython 作为有效的调试器
【发布时间】: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,允许我检查 ab 的值。

我想做的是每当我调用ipshell()自动运行以下代码:

frameinfo = getframeinfo(currentframe())
print 'Stopped at: ' + frameinfo.filename + ' ' +  str(frameinfo.lineno)

这将始终显示 IPython shell 启动的上下文,以便我知道我正在调试什么文件/函数等。

也许我可以使用装饰器来做到这一点,但到目前为止我的所有尝试都失败了,因为我需要 ipshell() 在原始上下文中运行 (这样我就可以访问 a和来自 IPython shell 的 b)。

我怎样才能做到这一点?

【问题讨论】:

  • Ipython 并不是真正的调试器。为什么不使用 python 调试器?

标签: python ipython


【解决方案1】:

您可以从另一个用户定义的函数中调用ipshell(),例如ipsh()

from inspect import currentframe

def ipsh():
    frame = currentframe().f_back
    msg = 'Stopped at {0.f_code.co_filename} and line {0.f_lineno}'.format(frame)
    ipshell(msg,stack_depth=2) # Go back one level!

然后在您想要进入 IPython shell 时使用ipsh()

说明:

  • 在检索新 IPython shell 的命名空间时,stack_depth=2 要求 ipshell 上一级(默认为 1)。
  • currentframe().f_back() 检索上一帧,以便您可以打印调用ipsh() 的位置的行号和文件。

【讨论】:

  • currentframe() 来自哪里?
  • 回答我自己的问题:from inspect import currentframe
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多