цветовые терминальные текстовые эффекты с Python - PullRequest
0 голосов
/ 29 ноября 2011

Я пытаюсь реализовать цветовую циклизацию в моем тексте на Python, т.е. я хочу, чтобы он циклически изменял цвет каждого набранного символа (среди других эффектов). Мой прогресс до сих пор был взломан вместе с цветом ansi рецепт предложения по улучшению приветствуются.

Я также был смутно осведомлен, но никогда не использовал: termcolor , colorama , curses

во время взлома мне удалось заставить атрибуты не работать (т. Е. Обратное мигание и т. Д.), И они не были идеальными, вероятно, в основном из-за того, что я неправильно понимаю эти строки:

cmd.append(format % (colours[tmpword]+fgoffset))

c=format % attrs[tmpword] if tmpword in attrs else None

если кто-нибудь сможет немного прояснить это, я был бы признателен. это работает и делает что-то, но это не совсем там. Я изменил код, поэтому вместо того, чтобы отделять цветовые команды от вашей строки, вы можете включить их.

 #!/usr/bin/env python

'''
        "arg" is a string or None
        if "arg" is None : the terminal is reset to his default values.
        if "arg" is a string it must contain "sep" separated values.
        if args are found in globals "attrs" or "colors", or start with "@" \
    they are interpreted as ANSI commands else they are output as text.
        @* commands:

            @x;y : go to xy
            @    : go to 1;1
            @@   : clear screen and go to 1;1
        @[colour] : set foreground colour
        ^[colour] : set background colour

        examples:
    echo('@red')                  : set red as the foreground color
    echo('@red ^blue')             : red on blue
    echo('@red @blink')            : blinking red
    echo()                       : restore terminal default values
    echo('@reverse')              : swap default colors
    echo('^cyan @blue reverse')    : blue on cyan <=> echo('blue cyan)
    echo('@red @reverse')          : a way to set up the background only
    echo('@red @reverse @blink')    : you can specify any combinaison of \
            attributes in any order with or without colors
    echo('@blink Python')         : output a blinking 'Python'
    echo('@@ hello')             : clear the screen and print 'hello' at 1;1

colours:
{'blue': 4, 'grey': 0, 'yellow': 3, 'green': 2, 'cyan': 6, 'magenta': 5, 'white': 7, 'red': 1}



    '''

'''
    Set ANSI Terminal Color and Attributes.
'''
from sys import stdout
import random
import sys
import time

esc = '%s['%chr(27)
reset = '%s0m'%esc
format = '1;%dm'
fgoffset, bgoffset = 30, 40
for k, v in dict(
    attrs = 'none bold faint italic underline blink fast reverse concealed',
    colours = 'grey red green yellow blue magenta cyan white'
).items(): globals()[k]=dict((s,i) for i,s in enumerate(v.split()))
bpoints = ( " [*] ", " [!] ", )

def echo(arg=None, sep=' ', end='\n', rndcase=True, txtspeed=0.03, bnum=0):

    cmd, txt = [reset], []
    if arg:
            if bnum != 0:
                    sys.stdout.write(bpoints[bnum-1])

        # split the line up into 'sep' seperated values - arglist
            arglist=arg.split(sep)

        # cycle through arglist - word seperated list 
            for word in arglist:

                if word.startswith('@'):
            ### First check for a colour command next if deals with position ###
                # go through each fg and bg colour  
                tmpword = word[1:]
                    if tmpword in colours:
                        cmd.append(format % (colours[tmpword]+fgoffset))
                    c=format % attrs[tmpword] if tmpword in attrs else None
                    if c and c not in cmd:
                                cmd.append(c)
                    stdout.write(esc.join(cmd))
                    continue
                # positioning (starts with @)
                word=word[1:]
                if word=='@':
                    cmd.append('2J')
                    cmd.append('H')
                    stdout.write(esc.join(cmd))
                    continue
                else:
                    cmd.append('%sH'%word)
                    stdout.write(esc.join(cmd))
                    continue

                if word.startswith('^'):
            ### First check for a colour command next if deals with position ###
                # go through each fg and bg colour  
                tmpword = word[1:]
                    if tmpword in colours:
                        cmd.append(format % (colours[tmpword]+bgoffset))
                    c=format % attrs[tmpword] if tmpword in attrs else None
                    if c and c not in cmd:
                                cmd.append(c)
                    stdout.write(esc.join(cmd))
                    continue                    
            else:
                for x in word:  
                    if rndcase:
                        # thankyou mark!
                        if random.randint(0,1):
                                x = x.upper()
                        else:
                            x = x.lower()
                    stdout.write(x)
                    stdout.flush()
                    time.sleep(txtspeed)
                stdout.write(' ')
                time.sleep(txtspeed)
    if txt and end: txt[-1]+=end
    stdout.write(esc.join(cmd)+sep.join(txt))

if __name__ == '__main__':

    echo('@@') # clear screen
    #echo('@reverse') # attrs are ahem not working
    print 'default colors at 1;1 on a cleared screen'
    echo('@red hello this is red')
    echo('@blue this is blue @red i can ^blue change @yellow blah @cyan the colours in ^default the text string')
    print
    echo()
    echo('default')
    echo('@cyan ^blue cyan blue')
    print
    echo()
    echo('@cyan this text has a bullet point',bnum=1)
    print
    echo('@yellow this yellow text has another bullet point',bnum=2)
    print
    echo('@blue this blue text has a bullet point and no random case',bnum=1,rndcase=False)
    print
    echo('@red this red text has no bullet point, no random case and no typing effect',txtspeed=0,bnum=0,rndcase=False)
#   echo('@blue ^cyan blue cyan')
    #echo('@red @reverse red reverse')
#    echo('yellow red yellow on red 1')
#    echo('yellow,red,yellow on red 2', sep=',')
#    print 'yellow on red 3'

#        for bg in colours:
#                echo(bg.title().center(8), sep='.', end='')
#                for fg in colours:
#                        att=[fg, bg]
#                        if fg==bg: att.append('blink')
#                        att.append(fg.center(8))
#                        echo(','.join(att), sep=',', end='')

    #for att in attrs:
    #   echo('%s,%s' % (att, att.title().center(10)), sep=',', end='')
    #   print

    from time import sleep, strftime, gmtime
    colist='@grey @blue @cyan @white @cyan @blue'.split()
    while True:
        try:
            for c in colist:
                sleep(.1)
                echo('%s @28;33 hit ctrl-c to quit' % c,txtspeed=0)
                echo('%s @29;33 hit ctrl-c to quit' % c,rndcase=False,txtspeed=0)
            #echo('@yellow @6;66 %s' % strftime('%H:%M:%S', gmtime()))
        except KeyboardInterrupt:
            break
        except:
            raise
    echo('@10;1')
    print

должен также упомянуть, что я абсолютно не знаю, что делает эта строка :) - хорошо, я вижу, что она помещает цвета в объект словаря, но то, как это происходит, сбивает с толку. еще не используется для этого синтаксиса Python.

for k, v in dict(
    attrs = 'none bold faint italic underline blink fast reverse concealed',
    colours = 'grey red green yellow blue magenta cyan white'
).items(): globals()[k]=dict((s,i) for i,s in enumerate(v.split()))

1 Ответ

0 голосов
/ 29 ноября 2011

Это довольно запутанный код - но, оставив вам вопрос о строках:

cmd.append(format % (colours[tmpword]+fgoffset))

Это выражение добавляет к списку с именем cmd интерполяцию строки, содержащейся в переменной format, с результатом выражения (colours[tmpword]+fgoffset)) - который объединяет код в таблице цветов (цветов), названной tmpword с fgoffset.

Строка format содержит '1;%dm', что означает, что она ожидает целое число, которое заменит "% d" внутри нее. (Подстановка строки % Python наследуется от форматирования printf в C). Вы «окрашиваете» таблицу цветов, с другой стороны, она построена в запутанном виде, я бы не советовал ни в каком коде, устанавливая для нее запись в «глобальных» значениях, но давайте предположим, что она имеет правильное числовое значение для каждой записи цвета. В этом случае добавление его к fgoffset приведет к созданию цветовых кодов вне диапазона (IRCC, выше 15) для некоторых цветовых кодов и смещений.

Теперь вторая строка, в которой вы сомневаетесь:

c=format % attrs[tmpword] if tmpword in attrs else None

Этот if является просто троичным оператором Python - эквивалентно C'ish expr?:val1: val2

Это эквивалентно:

если tmpword в attrs: c = формат% attrs [tmpword] еще: c = формат% нет

Обратите внимание, что он имеет меньший приоритет, чем оператор %. Может быть, вы бы предпочли:

c= (format % attrs[tmpword]) if tmpword in attrs else ''

вместо

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...