2018年7月24日 星期二

[ Python 常見問題 ] Print in terminal with colors?

Source From Here 
Question 
How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block? 

How-To 
One easier option would be to use the cprint function from termcolor package: 
>>> from termcolor import cprint
>>> cprint('john', 'red')
john
>>> cprint('ken', 'green')
ken
>>> cprint('%s is %d years-old' % ('john', 37), 'blue')
john is 37 years-old

Or you can define a string that starts a color and a string that ends the color, then print your text with the start string at the front and the end string at the end: 
  1. CRED = '\033[91m'  
  2. CEND = '\033[0m'  
  3. print(CRED + "Error, does not compute!" + CEND)  
This produces the following in bash, in urxvt with a Zenburn-style color scheme: 
 

Through experemintation, we can get more colors: 
 

This way we can create a full color collection: 
  1. CEND      = '\33[0m'  
  2. CBOLD     = '\33[1m'  
  3. CITALIC   = '\33[3m'  
  4. CURL      = '\33[4m'  
  5. CBLINK    = '\33[5m'  
  6. CBLINK2   = '\33[6m'  
  7. CSELECTED = '\33[7m'  
  8.   
  9. CBLACK  = '\33[30m'  
  10. CRED    = '\33[31m'  
  11. CGREEN  = '\33[32m'  
  12. CYELLOW = '\33[33m'  
  13. CBLUE   = '\33[34m'  
  14. CVIOLET = '\33[35m'  
  15. CBEIGE  = '\33[36m'  
  16. CWHITE  = '\33[37m'  
  17.   
  18. CBLACKBG  = '\33[40m'  
  19. CREDBG    = '\33[41m'  
  20. CGREENBG  = '\33[42m'  
  21. CYELLOWBG = '\33[43m'  
  22. CBLUEBG   = '\33[44m'  
  23. CVIOLETBG = '\33[45m'  
  24. CBEIGEBG  = '\33[46m'  
  25. CWHITEBG  = '\33[47m'  
  26.   
  27. CGREY    = '\33[90m'  
  28. CRED2    = '\33[91m'  
  29. CGREEN2  = '\33[92m'  
  30. CYELLOW2 = '\33[93m'  
  31. CBLUE2   = '\33[94m'  
  32. CVIOLET2 = '\33[95m'  
  33. CBEIGE2  = '\33[96m'  
  34. CWHITE2  = '\33[97m'  
  35.   
  36. CGREYBG    = '\33[100m'  
  37. CREDBG2    = '\33[101m'  
  38. CGREENBG2  = '\33[102m'  
  39. CYELLOWBG2 = '\33[103m'  
  40. CBLUEBG2   = '\33[104m'  
  41. CVIOLETBG2 = '\33[105m'  
  42. CBEIGEBG2  = '\33[106m'  
  43. CWHITEBG2  = '\33[107m'  
Here is the code to generate the test: 
  1. x = 0  
  2. for i in range(24):  
  3.   colors = ""  
  4.   for j in range(5):  
  5.     code = str(x+j)  
  6.     colors = colors + "\33[" + code + "m\\33[" + code + "m\033[0m "  
  7.   print(colors)  
  8.   x=x+5  


Supplement 
URxvt 和 Bash 的自定义配色

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...