ANSI Escape Codes in Python
ANSI escape codes are surprisingly useful. For Python, the escape code is "\x1b[". Here is an example loading bar. This is a Unix thing, won't work on windows.
Here "\x1b[34" is "colour foreground red", and "\x1b[8C" means move the cursor right 8 spaces"
It prints out something like this, but with loading in red:
loading[..........]
http://en.wikipedia.org/wiki/ANSI_escape_code
sys.stderr.write("\x1b[34mloading[" + " "*10 + "]\x1b[0m\r")
sys.stderr.write("\x1b[8C")
for i in range(10):
sys.stderr.write('.')
sys.stderr.write('\n')
Here "\x1b[34" is "colour foreground red", and "\x1b[8C" means move the cursor right 8 spaces"
It prints out something like this, but with loading in red:
loading[..........]
http://en.wikipedia.org/wiki/ANSI_escape_code
2 Comments:
Just a note for anyone else who comes across this: the sequence is actually recognized by python as 4 (or 5) distinct characters: '\x1b', '[', '#' (may be omitted), '#', and 'm'.
;-)
By Nobu, at 6:15 PM
Have you ever run across a library that does the opposite? I have a string that contains a bunch of ANSI escape codes, and I would like some code that can interpret them so that the string is cleaned up. I only want the final output, without any backspaces or other junk.
By Jeffrey Chang, at 3:09 PM
Post a Comment
<< Home