2010-11-18 36 views
2

我在瀏覽Django的源代碼,我看到這個功能:ANSI圖形代碼和Python

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,所以我認爲終端應該支持顏色。

+0

你還記得複製'前景','背景'和'opt_dict'?另外,'curses'。 – 2010-11-18 20:12:20

+0

是的,我做了,我會看着詛咒,謝謝:) – gmunk 2010-11-18 20:14:08

回答

1

這就是說你有很多未定義的術語,因爲它依賴於函數外定義的幾個變量。

,而不是僅僅

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 
+0

感謝您的評論,我用這些行復制功能,它似乎並沒有工作。也許我做錯了什麼,我會試着看看詛咒,看看會發生什麼。乾杯 – gmunk 2010-11-18 20:32:33

+0

@gmunk你有沒有注意到最近的編輯。 (例如,你明確地'打印'字符串,而不是僅僅用字符串引號來查看它)。 – 2010-11-18 20:33:51

+0

您或您的控制檯是否設置爲通過轉義序列來支持ANSI文本終端控件? – martineau 2010-11-18 20:54:15