How do I print colored output to the terminal in Python?

前端 未结 7 1045
日久生厌
日久生厌 2020-12-04 17:55

Is there any python equivalent for perl\'s

print color \'red\';
print ;
print color \'reset\';

available in python?

<
7条回答
  •  粉色の甜心
    2020-12-04 18:13

    I suggest sty. It's similar to colorama, but less verbose and it supports 8bit and 24bit colors. You can also extend the color register with your own colors.

    Examples:

    from sty import fg, bg, ef, rs
    
    foo = fg.red + 'This is red text!' + fg.rs
    bar = bg.blue + 'This has a blue background!' + bg.rs
    baz = ef.italic + 'This is italic text' + rs.italic
    qux = fg(201) + 'This is pink text using 8bit colors' + fg.rs
    qui = fg(255, 10, 10) + 'This is red text using 24bit colors.' + fg.rs
    
    # Add custom colors:
    
    from sty import Style, RgbFg
    
    fg.orange = Style(RgbFg(255, 150, 50))
    
    buf = fg.orange + 'Yay, Im orange.' + fg.rs
    
    print(foo, bar, baz, qux, qui, buf, sep='\n')
    

    Demo:

提交回复
热议问题