修饰符,用于修改python中函数打印的输出

修饰符,用于修改python中函数打印的输出,python,Python,假设我有一个打印五行文本的函数。我想为控制台上打印的每一行添加前缀,比如'asdf'和后缀'qwerty'。如何在python中使用decorator实现这一点。生成的输出可以来自我们想要修饰的函数中的日志模块或打印语句 def my_decorator(func): def wrapping_func(strlist): for index, i in enumerate(strlist): strlist[index] = 'wubalubad

假设我有一个打印五行文本的函数。我想为控制台上打印的每一行添加前缀,比如'asdf'和后缀'qwerty'。如何在python中使用decorator实现这一点。生成的输出可以来自我们想要修饰的函数中的日志模块或打印语句

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
仅修改给定给函数的参数,即添加前缀并返回,而使用
my_decorator
函数调用原始函数时,修改后的参数仅返回
wrapping_func
,下面是一个示例代码来演示此问题。 打印语句输出是自定义的,但不是来自日志模块的语句

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

我们发现日志模块的输出不是定制的。

如果您阅读了一个很好的decorator教程,甚至是python文档本身,如果你知道如何实现一个decorator,那么这个问题就会由你的直觉来解决。我可能会用StringIO替换stdout的
write
方法,而不是替换整个stdout流。您可以,而且它可以正常工作,但是您将延迟查看任何输出,直到函数完整完成为止。另一方面,替换
write
,可以让您在包装函数发出输出后立即看到它。我认为您还没有理解这个问题,或者您还没有注意到。您正在将输入修改为只打印给定字符串作为输入的函数。正如我在问题中提到的,控制台的输出可以来自日志记录also@RaghuRam你需要在问题中更准确地解释你想要什么。如果你按照例句去做。。我给你的,你要的东西与装饰师无关,你可以用不同的问题来提问,例如。。向控制台等提供输出