使用IPython作为有效的调试工具

2024-09-29 22:46:48 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在代码中嵌入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()来启动完整的ipythonshell。例如,以下代码:

^{pr2}$

在调用者范围内启动一个IPython shell,它允许我检查a和{}的值。在

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

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

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

也许我可以用decorator来完成这项工作,但是到目前为止,我的所有尝试都失败了,因为我需要ipshell()在原始上下文中运行(这样我就可以从ipythonshell访问a和{})。在

我怎样才能做到这一点?在


Tags: 代码inyouconfigipythonexittemplatemsg
1条回答
网友
1楼 · 发布于 2024-09-29 22:46:48

您可以从另一个用户定义函数中调用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!

然后,当您想进入ipythonshell时,请使用ipsh()。在

说明:

  • stack_depth=2请求ipshell在检索新ipythonshell的名称空间时向上一级(默认值是1)。在
  • currentframe().f_back()检索前一帧,这样您就可以打印出调用ipsh()的位置的行号和文件。在

相关问题 更多 >

    热门问题