termcolor.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # vim:set et sw=4:
  2. """
  3. TermColor utils for dak
  4. @contact: Debian FTP Master <ftpmaster@debian.org>
  5. @copyright: 2019 Mo Zhou <lumin@debian.org>
  6. @license: GNU General Public License version 2 or later
  7. """
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation; either version 2 of the License, or
  11. # (at your option) any later version.
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program; if not, write to the Free Software
  18. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  19. ###############################################################################
  20. __all__ = []
  21. ###############################################################################
  22. _COLORS_ = ('red', 'green', 'yellow', 'blue', 'violet', 'cyan', 'white')
  23. _COLOR_CODES_ = {k: 31 + _COLORS_.index(k) for k in _COLORS_}
  24. def colorize(s, fg, bg=None, bold=False, ul=False):
  25. '''
  26. s: str -- string to be colorized
  27. fg: str/int -- foreground color. See _COLORS_ for choices
  28. bg: str/int -- background color. See _COLORS_ for choices
  29. bold: bool -- bold font?
  30. ul: bool -- underline?
  31. '''
  32. if fg not in _COLORS_:
  33. raise ValueError("Unsupported foreground Color!")
  34. if (bg is not None) or any((bold, ul)):
  35. raise NotImplementedError
  36. return "\x1b[{}m{}\x1b[0;m".format(_COLOR_CODES_[fg], s)