簡體   English   中英

ANSI圖形代碼和Python

[英]ANSI graphic codes and Python

我正在瀏覽Django源代碼,並且看到了以下功能:

def colorize(text='', opts=(), **kwargs):
    """
    Returns your text, enclosed in ANSI graphics codes.

    Depends on the keyword arguments 'fg' and 'bg', and the contents of
    the opts tuple/list.

    Returns the RESET code if no parameters are given.

    Valid colors:
    'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'

    Valid options:
    'bold'
    'underscore'
    'blink'
    'reverse'
    'conceal'
    'noreset' - string will not be auto-terminated with the RESET code

    Examples:
    colorize('hello', fg='red', bg='blue', opts=('blink',))
    colorize()
    colorize('goodbye', opts=('underscore',))
    print colorize('first line', fg='red', opts=('noreset',))
    print 'this should be red too'
    print colorize('and so should this')
    print 'this should not be red'
    """
    code_list = []
    if text == '' and len(opts) == 1 and opts[0] == 'reset':
        return '\x1b[%sm' % RESET       
    for k, v in kwargs.iteritems(): 
        if k == 'fg':
            code_list.append(foreground[v]) 
        elif k == 'bg':
            code_list.append(background[v]) 
    for o in opts:
        if o in opt_dict:
            code_list.append(opt_dict[o])   
    if 'noreset' not in opts:
        text = text + '\x1b[%sm' % RESET
    return ('\x1b[%sm' % ';'.join(code_list)) + text

我將其從上下文中刪除,並放置在另一個文件中只是為了嘗試它,但事實是它似乎並沒有為我傳遞的文本着色。 可能是我不正確理解它,但難道它不應該只是返回被ANSI圖形代碼包圍的文本,然后終端將其轉換為實際顏色。

我嘗試了所有給定的調用它的示例,但是它只是返回了我指定為文本的參數。

我正在使用Ubuntu,因此我認為終端應支持顏色。

因為您有許多未定義的術語,因為它依賴於函數外部定義的多個變量。

而是

import django.utils.termcolors as termcolors
red_hello = termcolors.colorize("Hello", fg='red') # '\x1b[31mHello\x1b[0m'
print red_hello

或者只是也專門復制django / utils / termcolors.py的前幾行:

color_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white')
foreground = dict([(color_names[x], '3%s' % x) for x in range(8)])
background = dict([(color_names[x], '4%s' % x) for x in range(8)])
RESET = '0'

def colorize( ... ):
    ...
print colorize("Hello", fg='red') # '\x1b[31mHello\x1b[0m'

另請注意:

>>> from django.utils.termcolors import colorize
>>> red_hello = colorize("Hello", fg="red")
>>> red_hello # by not printing; it will not appear red; special characters are escaped
'\x1b[31mHello\x1b[0m'
>>> print red_hello # by print it will appear red; special characters are not escaped
Hello

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM