0
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?

  • Well since you are using executor to call `f` and you are doing nothing with variables directly, no. Also printing colored text in the console is platform specific(ish): https://stackoverflow.com/a/287944/8382028 – ViaTech Aug 03 '23 at 11:55
  • @ViaTech can I modify `f` before calling it, to add color? – Parth Mandaliya Aug 03 '23 at 12:44

2 Answers2

0

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)

Hoodlum
  • 950
  • 2
  • 13
0

You can use ANSI Code in python3.x.

print("\033[91m{0},{1}\033[00m".format("hello", "world"))

enter image description here

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.

jqknono
  • 84
  • 4