Python:如何从变量中获取信息

时间:2012-06-18 19:14:52

标签: python reflection python-internals

好的,这可能是个难题。而且我不希望你为我做所有艰苦的工作。我只是想提出一些好的建议和要点,我应该从哪里开始。

我正在编写几个python程序,我正在调试这些程序。所以我想创建一个简单的调试函数来记录一些事情。

这就是我使用它的方式:

# Defined in random_function_definitios.py
def some_random_function():
  a = 1 + 1
  debug(a)
  # More stuff

我想在调试中显示这些信息:

  • 调用它的函数:some_random_function
  • 定义该函数的文件名:random_function_definitios.py
  • 行号:4
  • 某些上下文:定义了全局变量并定义了局部变量。

我一直在看看检查模块和框架内置对象。但我不能完全确定我是否朝着正确的方向前进。

谢谢!

2 个答案:

答案 0 :(得分:2)

您可以使用Python的标准日志记录工具。大量数据带有日志记录 - 文档中提供了完整的列表:http://docs.python.org/library/logging.html#logrecord-attributes。您需要的是funcNamefilenamelineno。要记录本地变量的转储,您可以转换为内置函数locals()的字符串输出,并将其用作日志消息。您需要做的就是使用一个记录器,如:

import logging

logger = logging.getLogger('some_module')

def some_random_function():
    a = 1 + 1
    logger.debug(str(locals()))

使用前面提到的格式属性以适当的格式配置它。所有这些都在基本日志教程中有详细记录:http://docs.python.org/howto/logging.html#logging-basic-tutorial

修改

但如果我是你,我会在调试的上下文中启动python调试器来检查你想要交互式检查的所有内容:

def some_random_function():
    a = 1 + 1
    import pdb; pdb.set_trace()

答案 1 :(得分:2)

我使用info / warning和debug消息编写了自己的debugger.py。

请参阅:https://github.com/unixunion/toolbox/blob/master/python/debugger.py

我还使用回溯来遍历堆栈,如:

except Exception, e:
    # capture the traceback data
    exc_type, exc_value, exc_traceback = sys.exc_info()
    warningMsg("-14 %s" % str(e))
    warningMsg("Exec Traceback")
    traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
    warningMsg("Exception")
    traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout)
    raise

给出如下结果:

WARNING fabfile.py:76 glassfish_deploy()-14 cannot concatenate 'str' and 'float' objects
WARNING fabfile.py:77 glassfish_deploy()Exec Traceback
File "/home/marzubus/go-agent-scripts/fabfile.py", line 52, in glassfish_deploy    oiled =     gfOil(**kwargs)
WARNING fabfile.py:79 glassfish_deploy()Exception
Traceback (most recent call last):  File "/home/marzubus/go-agent-scripts/fabfile.py",    line 52, in glassfish_deploy
oiled = gfOil(**kwargs)
File "/home/marzubus/go-agent-scripts/oilon/gfdeployer.py", line 37, in __init__
self.tmpDirectory = '/tmp/' + self.domainName + self.time
TypeError: cannot concatenate 'str' and 'float' objects

基根