V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
poke707
V2EX  ›  Python

函数体里面能获取当前函数名称,被谁 call 等等的信息吗?

  •  
  •   poke707 ·
    Ginhing · 2014-06-19 14:11:40 +08:00 · 2867 次点击
    这是一个创建于 3605 天前的主题,其中的信息可能已经有所发展或是发生改变。
    试下贴代码.能成不?
    http://gist.github.com/334765c1c24375c4073a

    在用ide调试的时候见到一些function object具有诸如func_name,func_code之类的.
    这些在运行之前能否引用?
    6 条回复    2014-06-21 21:00:41 +08:00
    paulw54jrn
        1
    paulw54jrn  
       2014-06-19 14:13:29 +08:00
    http://stackoverflow.com/questions/10330119/how-to-backtrace-a-function-in-python-2-7
    搬运工

    import traceback

    def foo():
    bar()

    def bar():
    baz()

    def baz():
    traceback.print_stack()
    # or trace = traceback.extract_stack()

    foo()
    poke707
        2
    poke707  
    OP
       2014-06-19 14:21:35 +08:00
    @paulw54jrn 这个不太合适,我想的是在函数体内把"纯净的"函数状态引用出来
    比如foo=__func__这样
    YufunHe
        4
    YufunHe  
       2014-06-19 14:33:11 +08:00
    reflect
    poke707
        5
    poke707  
    OP
       2014-06-19 14:52:56 +08:00
    @miaoever 是的,大概可以这样 def f(a=0):return f.func_name
    @YufunHe 反射还是高深了点...也多谢你的提示
    xylophone21
        6
    xylophone21  
       2014-06-21 21:00:41 +08:00
    import traceback

    def foo():
    bar()


    def bar():
    foobar()

    def foobar():
    traceback.print_stack()

    if __name__ == '__main__':
    foo()


    是要这个吗?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2255 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 09:23 · PVG 17:23 · LAX 02:23 · JFK 05:23
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.