栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从python调试器将变量保存到交互式名称空间

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从python调试器将变量保存到交互式名称空间

您可以通过引用外部解释器的堆栈框架并写入其框架全局变量来实现此目的。

给定一个带有断点的示例模块,该断点将我们踢入pdb:

my_module.py

def fun(arg):    import pdb; pdb.set_trace()    print arg

演示基本概念的示例:

    >>> import my_module    >>> my_module.fun(1)    > /Users/lukasgraf/src/stackoverflow/my_module.py(3)fun()    -> print arg    (Pdb) import sys    (Pdb) sys._getframe(0)    <frame object at 0x1032ab290>    # this is the current frame    (Pdb) sys._getframe(0).f_globals['__name__']    'my_module'    # Next outer frame    (Pdb) sys._getframe(1).f_globals['__name__']    'pdb'    # etc...    # In this example, frame 10 happens to be    # the one from the outer interpreter    (Pdb) sys._getframe(10).f_globals['__name__']    '__main__'

因此,这是一个快速而肮脏的函数,它会沿着栈中全局

'__name__'
值查找
'__main__'

debughelper.py

import sys# Be safe and define a maximum of frames we're trying to walk upMAX_frameS = 20def save_to_interactive(dct):    n = 0    # Walk up the stack looking for '__name__'    # with a value of '__main__' in frame globals    for n in range(MAX_frameS):        cur_frame = sys._getframe(n)        name = cur_frame.f_globals.get('__name__')        if name == '__main__': # Yay - we're in the stack frame of the interactive interpreter! # So we update its frame globals with the dict containing our data cur_frame.f_globals.update(dct) break

用法:

>>> import my_module>>> my_module.fun('foo')> /Users/lukasgraf/src/stackoverflow/my_module.py(3)fun()-> print arg(Pdb) import debughelper(Pdb) debughelper.save_to_interactive({'mykey': 42})(Pdb) cfoo# We continued PDB, so we're in the outer interpreter again>>> print mykey42>>>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/669342.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号