Labels

new blog 2.0

2009/11/28

Colorful output in expect.

If you want to change shell color attributes from expect make sure that you escape at least the first three characters of the ANSI color sequence. This is necessary due to the way expect interprets strings. For instance, if you try to declare the red color sequence like this:
set red "\x1b[1;31;40m"
expect will think that you forgot to close the square bracket. If you escape the square bracket and continue like this:
set red "\x1b\x5b1;31;40m"
expect will think that the following "1" belongs to the preceding"\x5b". The following trick can be used to quickly convert an un-escaped string to a fully hex-escaped one:
$ export RED="\x1b[1;31;40m"
$ python -c "print ''.join([r'\x%x' % ord(c) for c in \"$COLOR\"])"
\x1b\x5b\x31\x3b\x33\x31\x3b\x34\x30\x6d
ANSI sequence strings escaped this way can be further used in except scripts.

#!/usr/bin/env expect

# Colorful output from expect.
# Slawek Ligus

proc stripe_write {text} {
# This procedure prints every second character of a given
# string argument $text in red.

# RED="\x1b[1;31;40m"
set red "\x1b\x5b\x31\x3b\x33\x31\x3b\x34\x30\x6d"
# NORMAL="\x1b[1;0;40m"
set normal "\x1b\x5b\x31\x3b\x30\x3b\x34\x30\x6d"
for {set i 0} {$i < [string length $text]} {incr i 2} {
puts -nonewline "$red[string index $text $i]"
puts -nonewline "$normal[string index $text [expr $i+1]]"
}
puts -nonewline $normal
}

stripe_write " Expect in color. \n"
stripe_write " http://blog.ooz.ie/ \n"
stripe_write "=====================\n"

No comments: