0

I have a Python script with several outputs in the case of an error, and if the error occurs then I want the message to be printed in red. I used ANSI codes to do this, such as in the example below:

    except Exception as e:
        print(f"\033[1;31;40m An error occurred while verifying alerts: {str(e)}")

However, this makes ALL the following output in the shell red. I want it to just be the error messages, and the rest of the text is the default color, like this: enter image description here But instead it's looking like this: enter image description here As you can see, everything I type even after the program is done running becomes red. I'm editing the python file in VIM, and I can't figure out a way to use ANSI codes change just one color of the code. Is there a trick I'm missing? Or are ANSI color codes supposed to permanently change the color of all the text for that session in the shell?

The only solution I could think of so far was to put the ANSI code for white text color at the end of each error message so that the following text goes back to white, but obviously depending on custom viewing options in the shell the default text color will be different depending on the user running the program. So I'd prefer to find a way to make just one line red, that way the rest of the text is its natural default color.

Ann Flus
  • 13
  • 2

1 Answers1

1

You need to use the RESET ANSI code to reset applied style:

print(f"\033[1;31;40m An error occurred while verifying alerts: {str(e)}\033[0m")

I often use this cheatsheet for ANSI codes, the ESCAPE sequence is \033 in Python.

Gugu72
  • 2,052
  • 13
  • 35
  • 1
    I see, none of the pages I read and researched ever mentioned anything about a reset. Thank you! – Ann Flus Aug 23 '23 at 09:30
  • I was wondering if maybe you also knew how to change the color of the text within a table cell when the table is created through tabulate(table_data, tablefmt(grid))? Can ANSI codes be used for this? – Ann Flus Aug 23 '23 at 09:43
  • You would indeed need to use ANSI codes to change the color of the text for each of your values, and don't forget to reset it every time too – Gugu72 Aug 23 '23 at 09:58
  • if the values are variables, then where do I put the ANSI code? Right before the variable name? – Ann Flus Aug 24 '23 at 10:26
  • I'm unsure as I've never used tabulate module, but you probably have a 2-dimensional array (list of lists) right now, in which case I would suggest iterating over every value to add the color & reset codes — or you might have a callback function available for formatting in the tabulate module – Gugu72 Aug 24 '23 at 11:58