How to print colored text in Python?

前端 未结 30 2843
谎友^
谎友^ 2020-11-21 04:41

How can I output colored text to the terminal in Python?

30条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-21 05:05

    https://raw.github.com/fabric/fabric/master/fabric/colors.py

    """
    .. versionadded:: 0.9.2
    
    Functions for wrapping strings in ANSI color codes.
    
    Each function within this module returns the input string ``text``, wrapped
    with ANSI color codes for the appropriate color.
    
    For example, to print some text as green on supporting terminals::
    
        from fabric.colors import green
    
        print(green("This text is green!"))
    
    Because these functions simply return modified strings, you can nest them::
    
        from fabric.colors import red, green
    
        print(red("This sentence is red, except for " + \
              green("these words, which are green") + "."))
    
    If ``bold`` is set to ``True``, the ANSI flag for bolding will be flipped on
    for that particular invocation, which usually shows up as a bold or brighter
    version of the original color on most terminals.
    """
    
    
    def _wrap_with(code):
    
        def inner(text, bold=False):
            c = code
            if bold:
                c = "1;%s" % c
            return "\033[%sm%s\033[0m" % (c, text)
        return inner
    
    red = _wrap_with('31')
    green = _wrap_with('32')
    yellow = _wrap_with('33')
    blue = _wrap_with('34')
    magenta = _wrap_with('35')
    cyan = _wrap_with('36')
    white = _wrap_with('37')
    

提交回复
热议问题