From 77d19e68d4148cbee32756645c59ccf2fdc31f10 Mon Sep 17 00:00:00 2001 From: pux Date: Tue, 31 Mar 2020 12:32:41 +0200 Subject: add bbcode converter --- pyfarbpracht.py | 38 ++++++++++++++++++++++++++++++++++++-- test.py | 9 +++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/pyfarbpracht.py b/pyfarbpracht.py index bb5e041..62ef308 100755 --- a/pyfarbpracht.py +++ b/pyfarbpracht.py @@ -1,7 +1,9 @@ from os import linesep -# print with color support +# we can also do print(colored('green', msg), end='') for example... +# printc helps if You have a global color_enabled flag in Your program def printc(color, msg, no_newline=False, enable_color=False): + """like print but with color support (if enabled!)""" ret = str() if enable_color: ret += colored(color, msg) @@ -14,8 +16,8 @@ def printc(color, msg, no_newline=False, enable_color=False): print(ret, end=end) return ret -# print with color support def colored(color, msg): + """returns msg in ANSI color""" ret = str() c = 'default' if color == 'red': @@ -37,3 +39,35 @@ def colored(color, msg): # reset color ret += '\033[0m' return ret + +# When data contains ANSI color escape codes convert them to BBcode format +# e.g.: Foo bar baz [\033[0;31m + text + [\033[0m +# where 31 can be 31..36 31=red, 32=green, +# 33=yellow, 34=blue, 35=magenta, 36-cyan +# 0 resets back to standard +# we can map those three parts to [color=#abcdef] + text + [/color] +def convert_ansi_to_bbcode_colors(instr): + """convert ansi escape sequences in a string to bbcode tags""" + ansi_red = '\033[0;31m' + ansi_green = '\033[0;32m' + ansi_yellow = '\033[0;33m' + ansi_blue = '\033[0;34m' + ansi_magenta = '\033[0;35m' + ansi_cyan = '\033[0;36m' + ansi_end = '\033[0m' + + bb_red = '[color=#FF0000]' + bb_green = '[color=#00FF00]' + bb_yellow = '[color=#FFFF00]' + bb_blue = '[color=#0000FF]' + bb_magenta = '[color=#FF00FF]' + bb_cyan = '[color=#00FFFF]' + bb_end = '[/color]' + + return instr.replace(ansi_red, bb_red) \ + .replace(ansi_green, bb_green) \ + .replace(ansi_yellow, bb_yellow) \ + .replace(ansi_blue, bb_blue) \ + .replace(ansi_magenta, bb_magenta) \ + .replace(ansi_cyan, bb_cyan) \ + .replace(ansi_end, bb_end) diff --git a/test.py b/test.py index 3693134..380a5bb 100755 --- a/test.py +++ b/test.py @@ -11,5 +11,14 @@ def test(): print(ret) print(ret) + print('') + print('') + + print(pyfarbpracht.colored('green', 'print(colored(... test in green')) + print(pyfarbpracht.colored( \ + 'green', 'print(colored(... test in green no newline'), end='') + + + if __name__ == '__main__': test() -- cgit v1.2.2-1-g5e49