How to print colour/color in python?

前端 未结 8 1030
有刺的猬
有刺的猬 2020-12-01 18:38

New to both Python and StackOverflow, I\'d like a little help. I\'d like to print color in Python and have Googled but with little luck :( I\'ve been confused each time and

相关标签:
8条回答
  • 2020-12-01 19:19

    If you want to print to a terminal in color you have to use escape codes for the terminal you're using. For unix/linux systems you can use the curses module - or just use bash color codes directly as a part of your output string. There doesn't seem to be an easy way to do this in windows according to this question.

    0 讨论(0)
  • 2020-12-01 19:20

    If you just want a really simply and straightforward way to print ansi colors in the terminal you can check out the ansicolor package module:

    Install via pip

    $ pip install ansicolors
    

    Usage snippet

    from colors import red, green, blue
    print red('This is red')
    print green('This is green')
    print blue('This is blue')
    
    from colors import color
    for i in range(256):
        print color('Color #%d' % i, fg=i)
    

    Note about pip

    pip is a python package manager. If you don't have pip installed, you can install it with easy_install pip

    If you then find you don't have easy_install, then download this: http://peak.telecommunity.com/dist/ez_setup.py and do:

    python ez_setup.py
    easy_install pip
    

    Colors for windows command shell

    The above ansi colors will not work for you in a windows command shell. Try looking at this activestate code snippet

    0 讨论(0)
提交回复
热议问题