【问题标题】:Decorator to modify output printed by a function in python装饰器修改python中函数打印的输出
【发布时间】:2018-06-09 10:12:52
【问题描述】:

假设我有一个打印五行文本的函数。我想为它在控制台上打印的每一行添加像“asdf”这样的前缀和后缀“qwerty”。如何在 python 中使用装饰器来做到这一点。生成的输出可以来自日志模块或我们要装饰的函数中的打印语句。

【问题讨论】:

  • 如果你学习了一个好的装饰器教程,甚至是从 python 文档本身,这个问题会凭直觉告诉你
  • 如果你知道如何实现一个装饰器,为了解决你的问题,你可以找到here
  • 我可能会替换 stdout 的 write 方法,而不是用 StringIO 替换整个 stdout 流。你可以,它会正常工作,但你会延迟看到 any 输出,直到函数全部完成。另一方面,替换 write 可以让您在包装函数发出输出时立即看到输出。

标签: python


【解决方案1】:
def my_decorator(func):
    def wrapping_func(strlist):
        for index, i in enumerate(strlist):
            strlist[index] = 'wubalubadubdub' + i
        return func(strlist)
    return wrapping_func

@my_decorator
def fun(str_list):
    for i in str_list:
        print(i)

if __name__ == "__main__":
    fun(['a', 'b'])

重复的问题,但无论如何上面的代码就是你要找的,wrapping_func 只是修改了给函数的参数,即添加前缀并在使用 @987654323 使用修改后的参数调用原始函数时返回@函数只返回wrapping_func

【讨论】:

  • 我认为你没有理解问题或者你没有注意。您正在将输入修改为仅打印给定字符串作为输入的函数。正如我在问题中提到的,控制台的输出也可以来自日志记录
  • @RaghuRam 您需要在问题中更准确地解释您想要什么。如果您按照我给出的示例..,您所要求的内容与装饰器无关,并且可以在不同的问题中提出,例如.. 将输出提供给控制台等
【解决方案2】:

这里有一个示例代码来演示这个问题。 打印语句输出是自定义的,但不是来自日志模块的语句。

from contextlib import contextmanager
@contextmanager
def no_stdout():
    import sys
    old_stdout = sys.stdout
    class CustomPrint():
        def __init__(self, stdout):
            self.old_stdout = stdout

        def write(self, text):
            if len(text.rstrip()):
                self.old_stdout.write('custom Print--->'+ text)

    sys.stdout = CustomPrint(old_stdout)

    try:
        yield
    finally:
        sys.stdout = old_stdout

def fun():
    import logging
    logger = logging.getLogger("tester")
    logger.info("Test line from function")

print "BEFORE"
with no_stdout():
    print "WHY HELLO!\n"
    print "DING DONG!\n"
    import logging
    logger = logging.getLogger("test")
    logger.info(" Hello world")
    fun()
print "AFTER"

输出:

BEFORE
custom Print--->WHY HELLO!
custom Print--->DING DONG!
2018-06-11 15:52:30,088 (42092) test INFO -  Hello world
2018-06-11 15:52:30,092 (42092) tester INFO - Test line from function
AFTER

我们看到日志模块的输出不是自定义的。

【讨论】:

    猜你喜欢
    • 2015-09-13
    • 2018-01-19
    • 1970-01-01
    • 2014-09-10
    • 2012-07-28
    • 2020-10-09
    • 2018-10-25
    • 2011-09-05
    • 2015-11-21
    相关资源
    最近更新 更多