python - 使用 IPython 作为有效的调试器

标签 python ipython

如何在我的代码中嵌入 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() 来运行在原始上下文中(这样我可以从 IPython shell 访问 ab

我怎样才能做到这一点?

最佳答案

您可以调用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!

然后使用ipsh()每当您想进入 IPython shell 时。

说明:

  • stack_depth=2ipshell在为新的 IPython shell 检索 namespace 时上一级(默认为 1 )。
  • currentframe().f_back()检索前一帧,以便您可以打印ipsh()所在位置的行号和文件被称为。

关于python - 使用 IPython 作为有效的调试器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15669186/

相关文章:

python - 在 Mac OSX : No module named jinja2 上启动 iPython 时出错

matplotlib - cygwin : TclError: no display name and no $DISPLAY environment variable 上的 ipython --pylab

python - 使用log in numpy求解贷款偿还公式

python - SQLAlchemy 按相关对象过滤查询

python - 带有使用管理器方法的自定义查询集的 Django Prefetch

python - 是否可以默认将所有 Jupyter notebook cells 设为 bash 类型?

python - 查找强连通分量上的边数

python - 如何在笔记本选项卡pygtk中获取输入字段作为密码(*)

python - 如何将命令行参数传递给 ipython

python - 在 Python 模块中隐藏中间计算