【问题标题】:Why inspect.stack() does not work properly?为什么 inspect.stack() 不能正常工作?
【发布时间】:2014-11-23 22:45:36
【问题描述】:

我正在尝试写入当前执行函数的名称。但它不能正常工作。 当我将'print inspect.stack()[0][3]' 放在def func() 之后时,它可以工作,但是当我尝试将此命令放在 if 之后时,它什么也不打印。

import inspect

debug = True

def debug():
    print inspect.stack()[0][3]
    if debug==True:
        print "test"
        print inspect.stack()[0][3]

debug()

返回'debug' 但它应该返回

'debug'\n'test'\n'debug'

问题出在哪里?

【问题讨论】:

    标签: python stack


    【解决方案1】:

    定义函数时:

    def debug():
    

    您正在从全局范围中丢失对先前创建的变量 debug 的最后一个引用。您将 debug 变量从持有 True 的布尔值重新定义为函数引用。所以条件debug==True 不满足(因为debug 现在是一个函数,而不是布尔值)。因此只有第一个 print 语句有效(参见 an illustrative demo)。

    这将按预期工作,例如:

    import inspect
    
    debug = True
    
    def f():
        print inspect.stack()[0][3]
        if debug==True:
            print "test"
            print inspect.stack()[0][3]
    
    f()
    

    这是 Python 中的一个常见错误,尤其是对于习惯于其他语言的人来说,其中函数名称以特殊方式处理。在 Python 中它们不是 - 定义函数后,您可以将其名称用作任何其他变量。这有很多优点,但正如这里所见,有时可能会令人困惑。

    【讨论】:

      【解决方案2】:

      在 python 3 和 hight 中你需要使用 print() if。如果没有 (),它会变成语法错误,并且不会打印任何内容

      【讨论】:

      • OP 说代码运行没有错误,所以显然这与 Python 3 无关。
      猜你喜欢
      • 2016-07-16
      • 2019-01-04
      • 2020-09-03
      • 2016-10-10
      • 2016-10-24
      • 2017-02-27
      • 2017-07-08
      • 2021-03-07
      • 2021-01-24
      相关资源
      最近更新 更多