python --print带颜色输出
第一种【不支持linux】
- # -*- coding:utf-8 -*-
- print("\033[1;30m 字体颜色:白色\033[0m")
- print("\033[1;31m 字体颜色:红色\033[0m")
- print("\033[1;32m 字体颜色:深黄色\033[0m")
- print("\033[1;33m 字体颜色:浅黄色\033[0m")
- print("\033[1;34m 字体颜色:蓝色\033[0m")
- print("\033[1;35m 字体颜色:淡紫色\033[0m")
- print("\033[1;36m 字体颜色:青色\033[0m")
- print("\033[1;37m 字体颜色:灰色\033[0m")
- print("\033[1;38m 字体颜色:浅灰色\033[0m")
-
- print("背景颜色:白色 \033[1;40m \033[0m")
- print("背景颜色:红色 \033[1;41m \033[0m")
- print("背景颜色:深黄色 \033[1;42m \033[0m")
- print("背景颜色:浅黄色 \033[1;43m \033[0m")
- print("背景颜色:蓝色 \033[1;44m \033[0m")
- print("背景颜色:淡紫色 \033[1;45m \033[0m")
- print("背景颜色:青色 \033[1;46m \033[0m")
- print("背景颜色:灰色 \033[1;47m \033[0m")
-
第二种【支持跨平台】 推荐 自带标准库
- from colorama import init, Fore, Back, Style
-
- init(autoreset=True)
-
-
- class Log(object):
-
- # 前景色:红色 背景色:默认
- def red(self, s):
- return Fore.RED + s + Fore.RESET
-
- # 前景色:绿色 背景色:默认
- def green(self, s):
- return Fore.GREEN + s + Fore.RESET
-
- # 前景色:黄色 背景色:默认
- def yellow(self, s):
- return Fore.YELLOW + s + Fore.RESET
-
- # 前景色:蓝色 背景色:默认
- def blue(self, s):
- return Fore.BLUE + s + Fore.RESET
-
- # 前景色:洋红色 背景色:默认
- def magenta(self, s):
- return Fore.MAGENTA + s + Fore.RESET
-
- # 前景色:青色 背景色:默认
- def cyan(self, s):
- return Fore.CYAN + s + Fore.RESET
-
- # 前景色:白色 背景色:默认
- def white(self, s):
- return Fore.WHITE + s + Fore.RESET
-
- # 前景色:黑色 背景色:默认
- def black(self, s):
- return Fore.BLACK
-
- # 前景色:白色 背景色:绿色
- def white_green(self, s):
- return Fore.WHITE + Back.GREEN + s
-
- def dave(self, s):
- return Style.BRIGHT + Fore.GREEN + s
-
-
- color = Log()
- print(color.red('I am red!'))
- print(color.green('I am gree!'))
- print(color.yellow('I am yellow!'))
- print(color.blue('I am blue!'))
- print(color.magenta('I am magenta!'))
- print(color.cyan('I am cyan!'))
- print(color.white('I am white!'))
- print(color.white_green('I am white green!'))
- print(color.dave("www.cndba.cn"))
- print(111)
-
结果
第三种【第三方模块】
- pip install termcolor
-
-
- cprint('红色', 'red')
- cprint('白色', 'grey')
- cprint('绿色', 'green')
- cprint('黄色', 'yellow')
- cprint('蓝色', 'blue')
- cprint('紫色', 'magenta')
- cprint('青色', 'cyan')
- cprint('默认', 'white')
-
- cprint('背景白', on_color='on_grey')
- cprint('背景红', on_color='on_red')
- cprint('背景绿', on_color='on_green')
- cprint('背景黄', on_color='on_yellow')
- cprint('背景蓝', on_color='on_blue')
- cprint('背景紫', on_color='on_magenta')
- cprint('背景青', on_color='on_cyan')
- cprint('背景默认色', color='grey', on_color='on_white')
-
结果