2010-11-18 3 views
2

내가 장고 소스 코드를 검색하고 있었고, 난이 기능 보았다ANSI 그래픽 코드와 파이썬

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 그래픽 코드로 둘러싸인 텍스트를 반환하기로되어 있지는 않습니다.

나는 그것을 호출하는 모든 주어진 예제를 시도했지만 텍스트로 지정된 인수를 방금 반환했습니다.

저는 우분투를 사용하고 있으므로 터미널이 색상을 지원해야한다고 생각합니다.

+0

당신이 기억나요 '전경','배경','opt_dict'를 복사합니까? 또한,'curses'. –

+0

그래, 나는 저주로, 감사합니다 :) – gmunk

답변

1

많은 용어가 정의되지 않았습니다. 함수 외부에서 정의 된 여러 변수에 의존하기 때문입니다.

대신 단지

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

하거나 또한 장고/유틸/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

+0

@gmunk 최근 편집을 보았습니까? 예를 들어 문자열 인용 부호를 사용하여 문자열을 보는 것과 달리 문자열을 'print'ing합니다. –

+0

이스케이프 시퀀스를 통해 ANSI 텍스트 터미널 컨트롤을 지원하도록 콘솔을 설정 했습니까? – martineau