termcolor.py 1.7 KB

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