从追溯获取最后一个函数的调用参数? [英] Get last function's call arguments from traceback?

查看:189
本文介绍了从追溯获取最后一个函数的调用参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以获取在追溯中调用的最后一个函数的参数吗?如何?



我想制作标准错误的捕手来制作可读的代码,但可以向用户提供详细的信息。



在下面的例子中,我想要GET_PARAMS给我一个提供给os.chown的参数元组。检查Alex Martelli建议的检查模块,我找不到。

  def catch_errors(fn):
def decorator(* args,** kwargs):
try:
return fn(* args,** kwargs)
except( IOError,OSError):
msg = sys.exc_info()[2] .tb_frame.f_locals ['error_message']
quit(msg.format(SEQUENCE_OF_PARAMETERS_OF_THE_LAST_FUNCTION_CALLED)\
+'\ nError#{0 [0]}:{0 [1]}'。format(sys.exc_info()[1] .args),1)
return decorator

@catch_errors
def do_your_job():
error_message ='不能更改文件夹所有权\'{0} \'(uid:{1},gid:{2})'
os.chown('/ root',1000,1000)#注意,参数不是命名的vars。

如果__name =='__main__'和os.getenv('USERNAME')!='root':
do_your_job()
pre>

(感谢 Jim Robert 的装饰师)

解决方案

使用装饰器为您尝试实现的问题是异常处理程序获取的框架是 do_your_job() s,而不是 os.listdir() s, os.makedirs() / code> s或 os.chown() s。因此,您要打印的信息是 do_your_job()的参数。为了获得我认为你打算的行为,你必须装饰你正在调用的所有库函数。


Can I get the parameters of the last function called in traceback? How?

I want to make a catcher for standard errors to make readable code, yet provide detailed information to user.

In the following example I want GET_PARAMS to return me a tuple of parameters supplied to os.chown. Examining the inspect module advised by Alex Martelli, I couldn't find that.

def catch_errors(fn):
    def decorator(*args, **kwargs):
        try:
            return fn(*args, **kwargs)
        except (IOError, OSError):
            msg = sys.exc_info()[2].tb_frame.f_locals['error_message']
            quit(msg.format(SEQUENCE_OF_PARAMETERS_OF_THE_LAST_FUNCTION_CALLED)\
            + '\nError #{0[0]}: {0[1]}'.format(sys.exc_info()[1].args), 1)
    return decorator

@catch_errors
def do_your_job():
    error_message = 'Can\'t change folder ownership \'{0}\' (uid:{1}, gid:{2})'
    os.chown('/root', 1000, 1000) # note that params aren't named vars.

if __name == '__main__' and os.getenv('USERNAME') != 'root':
    do_your_job()

(Thanks to Jim Robert for the decorator)

解决方案

The problem with using a decorator for what you're trying to achieve is that the frame the exception handler gets is do_your_job()s, not os.listdir()s, os.makedirs()s or os.chown()s. So the information you'll be printing out is the arguments to do_your_job(). In order to get the behavior I think you intend, you would have to decorate all the library functions you're calling.

这篇关于从追溯获取最后一个函数的调用参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆