简体   繁体   English

如何记录变量的名称和值?

[英]How to log a variable's name and value?

I am looking for a way to quickly print a variable name and value while rapidly developing/debugging a small Python script on a Unix command line/ssh session.我正在寻找一种方法来快速打印变量名称和值,同时在 Unix 命令行/ssh session 上快速开发/调试小型 Python 脚本。

It seems like a very common requirement and it seems wasteful (on keystrokes and time/energy) to duplicate the variable_name s on every line which prints or logs its value.这似乎是一个非常普遍的要求,并且在打印或记录其值的每一行上复制variable_name似乎很浪费(在击键和时间/能量上)。 ie rather than即而不是

print 'my_variable_name:', my_variable_name

I want to be able to do the following for str , int , list , dict :我希望能够为strintlistdict执行以下操作:

log(my_variable_name)
log(i)
log(my_string)
log(my_list)

and get the following output:并获得以下 output:

my_variable_name:some string
i:10
my_string:a string of words
my_list:[1, 2, 3]

Ideally the output would also log the function name.理想情况下,output 也会记录 function 名称。

I have seen some solutions attempting to use locals , globals , frames etc., But I have not yet seen something that works for ints, strings, lists, and works inside functions too.我已经看到一些尝试使用localsglobals 、 frames 等的解决方案,但我还没有看到适用于 ints、strings、lists 和在函数内部工作的东西。

Thanks!谢谢!

If the tool you need is only for developing and debugging, there's a useful package calle q . 如果您需要的工具仅用于开发和调试,那么有一个有用的包calle q

It has been submitted to pypi, it can be installed with pip install q or easy_install q . 它已经提交给pypi,它可以用pip install qeasy_install q pip install q

import q; q(foo)

# use @q to trace a function's arguments and return value
@q
def bar():
   ...

# to start an interactive console at any point in your code:
q.d()

The results are output to the file /tmp/q(or any customized paths) by default,so they won't be mixed with stdout and normal logs. 默认情况下,结果将输出到文件/ tmp / q(或任何自定义路径),因此它们不会与stdout和普通日志混合使用。 You can check the output with tail -f /tmp/q . 您可以使用tail -f /tmp/q检查输出。 The output is highlighted with different colors. 输出以不同颜色突出显示。

The author introduced his library in a lightning talk of PyconUS 2013. The video is here , begins at 25:15. 作者在2013年的PyconUS闪电话中介绍了他的图书馆。视频在这里 ,从25:15开始。

Sorry to Necro this ancient thread, but this was surprisingly difficult to find a good answer for.对 Necro 这个古老的话题感到抱歉,但要找到一个好的答案却出奇地困难。

Using the '=' sign after the variable achieves this.在变量实现后使用“=”符号。 For instance:例如:

import pathlib as pl
import logging

logging.basicConfig(level=logging.DEBUG)

data_root = pl.Path("D:\Code_Data_Dev\Data\CSV_Workspace_Data")

logging.debug(f'{data_root=}')

This outputs这输出

DEBUG:root:data_root=WindowsPath('D:/Code_Data_Dev/Data/CSV_Workspace_Data')

Here is another evil hack: 这是另一个邪恶的黑客:

import inspect

def log(a):
    call_line = inspect.stack()[1][4][0].strip()
    assert call_line.strip().startswith("log(")
    call_line = call_line[len("log("):][:-1]
    print "Log: %s = %s" % (call_line, a)

b=3
log(b)

This obviously would need some range checks, better parsing, etc. Also works only if the calls is made always in the same way and has probably more - unknown to me - assumptions... 这显然需要一些范围检查,更好的解析等。只有当调用总是以相同的方式进行并且可能更多 - 我不知道 - 假设时...

I don't know any way to simply get the name of a variable of a string. 我不知道如何简单地获取字符串变量的名称。 you can however get the list of argument of the current fonction log. 但是,您可以获取当前fonction日志的参数列表。

import inspect

def log(a):
    frame = inspect.currentframe()
    args, _, _, values = inspect.getargvalues(frame)
    print "%s:%s" % (args[0], values[args[0]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM