2

I have this Python script for formatting and coloring output:

def error(message):
    print(f"\033[91m{message}\033[00m")


def warning(message):
    print(f"\033[93m{message}\033[00m")


def info(message):
    print(f"\033[96m{message}\033[00m")


def success(message):
    print(f"\033[92m{message}\033[00m")

And it works great when I write messages directly to the terminal.

However, some of my scripts are used indirectly in other shell scripts, and in that case, my output won't work properly.

For example, I have a Python script to find out the name of the OS. It's called GetOs and when executed, it would print Ubuntu in a blue color.

Now when I want to use this Python script in my Shell script as follow:

if [[ $(GetOs) == Ubuntu ]]; then
   echo "This feature is not supported on Ubuntu"
fi

it fails. The equality operator won't work because the $(GetOs) would return a blue result to the stdout.

Is it possible for me to conditionally color messages in my Message.py file? To know if it's being called from another script or directly from the terminal?

  • Did you try giving your Python program a command-line option, so that the shell script can explicitly tell it not to colour the messages? – Karl Knechtel May 09 '23 at 06:54
  • Does this answer your question? [how do I determine whether a python script is imported as module or run as script?](https://stackoverflow.com/questions/1389044/how-do-i-determine-whether-a-python-script-is-imported-as-module-or-run-as-scrip) – esqew May 09 '23 at 06:54
  • A better question to ask is "is standard output connected to a terminal"? But the simplest solution of all is to remove the annoying color coding. – tripleee May 09 '23 at 07:16

1 Answers1

2

Your real question is how your script can determine whether if the standard output is connected to a terminal, and then and only then it should wrap any given output in color codes.

For that purpose you can use the isatty method of the file object of the standard output, which returns True when the standard output is connected to a terminal, or False if it's redirected to a file or another process:

import sys

def info(message):
    if sys.stdout.isatty():
        print(f"\033[91m{message}\033[00m")
    else:
        print(message)
blhsing
  • 91,368
  • 6
  • 71
  • 106