def executor(f):
print("This is executor")
f()
def demo():
print("This is demo function")
executor(demo)
Is there any way to color the output of demo
function from executor
function without modifying the original function?
def executor(f):
print("This is executor")
f()
def demo():
print("This is demo function")
executor(demo)
Is there any way to color the output of demo
function from executor
function without modifying the original function?
I can think of one way to do this, but it's pretty janky, and might break stuff in fun and unexpected ways : you could redirect stdout
, as was shown in this question.
Once you've done that, you can retrieve whatever was printed during the time stdout was redirected, color it, and print it to your terminal using the termcolor package (suggested in the question referenced in the comments).
In code, that would be something like the following :
import io
import sys
import termcolor
def executor(f):
print("This is executor")
old_stdout = sys.stdout
buffer = io.StringIO()
# wrap in a try - finally, bc we really don't want
# to be left without a stdout if this fails
try:
sys.stdout = buffer
f()
finally:
sys.stdout = old_stdout
termcolor.cprint(buffer.getvalue(), "green")
def demo():
print("This is demo function")
executor(demo)
You can use ANSI Code in python3.x.
print("\033[91m{0},{1}\033[00m".format("hello", "world"))
Refer to ANSI escape code: Color
\033[
: This is an escape code, which is a way of producing non-printable characters such as color codes.
91m
: This is a color code that represents the color red in the terminal.
{0},{1}
: These are placeholders for the format() method. {0} is replaced by the first argument passed to format(), and {1} is replaced by the second argument passed to format().
\033[00m
: This resets the color back to the terminal's default color.
.format("hello", "world")
: This is a method which formats the string by replacing {0} and {1} with "hello" and "world" respectively.