Issue
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.
Solution
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.
Answered By - Gugu72 Answer Checked By - Dawn Plyler (WPSolving Volunteer)