修改包装函数中的函数代码

时间:2019-10-28 02:33:20

标签: python python-3.x decorator

是否可以用包装它的函数替换函数的实际代码?在这里,我尝试将print语句替换为log语句:

import logging
import re

def print_to_log(func):
    def wrapper_print_to_log(*args, **kwargs):
        # how to do something like this?
        re.sub(r'print\s*\(',  'logging.info(', **function_code**)
        return func(*args, **wargs)
    return wrapper_print_to_log


@print_to_log
def greet(name='bob'):
    print ("Hello, %s" % name)
    print ("How are you sir?")

是否可以替换代码或执行与上面类似的操作?

1 个答案:

答案 0 :(得分:0)

也许您可以临时替换sys.stdout?

import logging
import re
import sys
import io

def print_to_log(func):
    def wrapper_print_to_log(*args, **kwargs):
        stdout = sys.stdout
        b = io.StringIO()
        sys.stdout = b
        try:
            return func(*args, **kwargs)
        finally:
            sys.stdout = stdout
            print(b.getvalue().upper())

    return wrapper_print_to_log

@print_to_log
def greet(name='bob'):
    print("Hello, %s" % name)
    print("How are you sir?")

greet('justin')