这真的很棘手。让我尝试重用this code 给出一个更完整的答案,以及 Senthil 的答案中关于getargspec 的提示,这让我不知何故被触发了。顺便说一句,getargspec 在 Python 3.0 中已弃用,而getfullarcspec should be used 则改为。
这适用于我在 Python 3.1.2 上显式调用调试函数和使用装饰器:
# from: https://stackoverflow.com/a/4493322/923794
def getfunc(func=None, uplevel=0):
"""Return tuple of information about a function
Go's up in the call stack to uplevel+1 and returns information
about the function found.
The tuple contains
name of function, function object, it's frame object,
filename and line number"""
from inspect import currentframe, getouterframes, getframeinfo
#for (level, frame) in enumerate(getouterframes(currentframe())):
# print(str(level) + ' frame: ' + str(frame))
caller = getouterframes(currentframe())[1+uplevel]
# caller is tuple of:
# frame object, filename, line number, function
# name, a list of lines of context, and index within the context
func_name = caller[3]
frame = caller[0]
from pprint import pprint
if func:
func_name = func.__name__
else:
func = frame.f_locals.get(func_name, frame.f_globals.get(func_name))
return (func_name, func, frame, caller[1], caller[2])
def debug_prt_func_args(f=None):
"""Print function name and argument with their values"""
from inspect import getargvalues, getfullargspec
(func_name, func, frame, file, line) = getfunc(func=f, uplevel=1)
argspec = getfullargspec(func)
#print(argspec)
argvals = getargvalues(frame)
print("debug info at " + file + ': ' + str(line))
print(func_name + ':' + str(argvals)) ## reformat to pretty print arg values here
return func_name
def df_dbg_prt_func_args(f):
"""Decorator: dpg_prt_func_args - Prints function name and arguments
"""
def wrapped(*args, **kwargs):
debug_prt_func_args(f)
return f(*args, **kwargs)
return wrapped
用法:
@df_dbg_prt_func_args
def leaf_decor(*args, **kwargs):
"""Leaf level, simple function"""
print("in leaf")
def leaf_explicit(*args, **kwargs):
"""Leaf level, simple function"""
debug_prt_func_args()
print("in leaf")
def complex():
"""A complex function"""
print("start complex")
leaf_decor(3,4)
print("middle complex")
leaf_explicit(12,45)
print("end complex")
complex()
并打印:
start complex
debug info at debug.py: 54
leaf_decor:ArgInfo(args=[], varargs='args', keywords='kwargs', locals={'args': (3, 4), 'f': <function leaf_decor at 0x2aaaac048d98>, 'kwargs': {}})
in leaf
middle complex
debug info at debug.py: 67
leaf_explicit:ArgInfo(args=[], varargs='args', keywords='kwargs', locals={'args': (12, 45), 'kwargs': {}})
in leaf
end complex
装饰器有点作弊:因为在wrapped 中我们得到与函数本身相同的参数,所以我们在getfunc 和debug_prt_func_args 中找到并报告wrapped 的ArgSpec 并不重要。这段代码可以美化一点,但对于我使用的简单调试测试用例,它现在可以正常工作了。
您可以做的另一个技巧:如果您取消注释getfunc 中的for-loop,您会看到inspect 可以为您提供“上下文”,这实际上是调用函数的源代码行。这段代码显然没有显示给你的函数的任何变量的内容,但有时它已经有助于知道使用的变量名比你调用的函数高一级。
如您所见,使用装饰器您不必更改函数内部的代码。
您可能想要漂亮地打印参数。我在函数中保留了原始打印(以及注释掉的打印语句),因此更容易使用。