How to print colored text in Python?

前端 未结 30 2920
谎友^
谎友^ 2020-11-21 04:41

How can I output colored text to the terminal in Python?

30条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-21 05:16

    note how well the with keyword mixes with modifiers like these that need to be reset (using Python 3 and Colorama):

    from colorama import Fore, Style
    import sys
    
    class Highlight:
      def __init__(self, clazz, color):
        self.color = color
        self.clazz = clazz
      def __enter__(self):
        print(self.color, end="")
      def __exit__(self, type, value, traceback):
        if self.clazz == Fore:
          print(Fore.RESET, end="")
        else:
          assert self.clazz == Style
          print(Style.RESET_ALL, end="")
        sys.stdout.flush()
    
    with Highlight(Fore, Fore.GREEN):
      print("this is highlighted")
    print("this is not")
    

提交回复
热议问题