Reputation: 1764
Is it possible to replace the actual code of a function by the function that wraps it? Here I'm trying to replace print
statements with log
statements:
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?")
Is it possible to replace the code or do something similar to the above?
Upvotes: 1
Views: 268
Reputation:
Perhaps you can temporarily replace 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')
Upvotes: 1