【问题标题】:How to change an output?如何更改输出?
【发布时间】:2022-12-17 11:28:59
【问题描述】:

所以我的任务是:编写一个装饰器,记录有关装饰函数的调用、其参数值、关键字参数和执行时间的信息。日志应写入文件。

我的解决方案是:

``
from time import time

def log(func):
    def wrapper(*args, **kwargs):
        start_time = time()
        func(*args, **kwargs)
        end_time = time() - start_time
        with open('log.txt', 'a+') as file:
            file.write(f'{func.__name__}; args: {args}, kwargs: {kwargs}, execution time: {end_time}\n sec.')
    return wrapper
``

我必须用一个函数来测试它:

``
@log
def foo(a, b, c):
    ...

foo(1, 2, c=3)
``

log.txt 文件中的预期结果必须如下所示:

...
foo; args: a=1, b=2; kwargs: c=3; execution time: 0.12 sec.
...

但我得到的是:

some_fun; args: (1, 2), kwargs: {'c': 3}, execution time: 0.0
sec.

我应该如何更改我的代码以获得预期的结果?


【问题讨论】:

    标签: python python-3.x file logging decorator


    【解决方案1】:

    现在我认为这是不可能的,因为你正在做的是显示完整的 {kwargs} 和 {args},它们只会返回一个列表。

    对此的解决方案是,您将编写一个 for 循环并显示 {args} 和 {kwargs} 中的每个项目,并且暂时,您应该使用另一个函数而不是

    开始时间=时间();

    在 python 文档中找到其他函数: https://docs.python.org/3/library/time.html#module-time

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-21
      • 2014-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多