如何在代码中嵌入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。例如,以下代码:
在调用者范围内启动一个IPython shell,它允许我检查a
和{
我想做的是每当我调用ipshell()
时,自动运行以下代码:
frameinfo = getframeinfo(currentframe())
print 'Stopped at: ' + frameinfo.filename + ' ' + str(frameinfo.lineno)
这将始终显示ipythonshell启动的上下文,以便知道我正在调试的文件/函数等。在
也许我可以用decorator来完成这项工作,但是到目前为止,我的所有尝试都失败了,因为我需要ipshell()
在原始上下文中运行(这样我就可以从ipythonshell访问a
和{
我怎样才能做到这一点?在
您可以从另一个用户定义函数中调用
ipshell()
,例如ipsh()
然后,当您想进入ipythonshell时,请使用
ipsh()
。在说明:
stack_depth=2
请求ipshell
在检索新ipythonshell的名称空间时向上一级(默认值是1
)。在currentframe().f_back()
检索前一帧,这样您就可以打印出调用ipsh()
的位置的行号和文件。在相关问题 更多 >
编程相关推荐