0

I'm new to Python, trying to print a colored text in the console. My OS is windows 10. Here is the code:

class bcolors:
    """
    Colors for console
    """
    HEADER = '\033[95m'
    YGREEN = '\033[92m'
    WARNING = '\033[93m'
    ENDC = '\033[0m'

def main():
    user_name: str = input(
        f'***Hello {bcolors.YGREEN}friend{bcolors.ENDC} Welcome***\nPlease enter your Name:\n')

if __name__ == '__main__':
    main()

but when I execute this code either through CMD or PyCharm, I don't get colored text. Here is the output:

pic

What's wrong?

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Pablo
  • 465
  • 1
  • 4
  • 14

5 Answers5

2

I'd suggest you to use Printy instead:

Install:

pip3 install printy

Use it:

from printy import inputy

user_name = inputy("Hello [n]friend@, \n Please enter your name:)

the 'n' flag will apply a green color to the word friend. It is an OS independent library

1

Try using this in your main: print(bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC) Or this: print(f"{bcolors.WARNING}Warning: No active frommets remain. Continue?{bcolors.ENDC}")

Nick
  • 21
  • 2
1

This code only works on an XTerm-compliant Linux/Unix terminal. If you would like this code to work, see https://pypi.org/project/colorama.

import colorama
colorama.init(wrap=True)

class bcolors:
    """
    Colors for console
    """
    HEADER = '\033[95m'
    YGREEN = '\033[92m'
    WARNING = '\033[93m'
    ENDC = '\033[0m'

def main():
    print(f'***Hello {bcolors.YGREEN}friend{bcolors.ENDC} Welcome***\nPlease enter your Name:\n', end='')
    user_name: str = input()

if __name__ == '__main__':
    main()
not my real name
  • 393
  • 4
  • 16
0

If you prefer not installing anything, simply add this to the start of your code

import subprocess
subprocess.call('', shell=True)
0

you can use os as well :)

Here a solution works on Windows

this solution works in cmd, powershell

#first import os
import os
# make printing colors possible
os.system('')
# get an amzing reuslt :D
# '\033[44m' is the color
print('\033[44m'+'Test'+'\033[0m') # '\033[0m' the end of the color

I test it and it works perfectly

python -c "import os;os.system('');print('\033[34m'+'Test'+'\033[0m')"

cmd output

thanks to SimpleBinary for forging out.

if you don't want to write this code then you can use cmder

cmder allowed you to use colors without `os.system()'

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 11 '22 at 04:05