Python的Colorama模塊,能夠跨多終端,顯示字體不一樣的顏色和背景,只須要導入colorama模塊便可,不用再每次都像linux同樣指定顏色。python
pip install colorama
Fore是針對字體顏色,Back是針對字體背景顏色,Style是針對字體格式linux
Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET. Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET. Style: DIM, NORMAL, BRIGHT, RESET_ALL
注意,顏色RED,GREEN都須要大寫,先指定是顏色和樣式是針對字體仍是字體背景,而後再添加顏色,顏色就是英文單詞指定的顏色 git
from colorama import Fore, Back, Style print(Fore.RED + 'some red text') print(Back.GREEN + 'and with a green background') print(Style.DIM + 'and in dim text') print(Style.RESET_ALL) print('back to normal now')
輸出結果windows
# 記得要及時關閉colorma的做用範圍
# 若是不關閉的話,後面全部的輸出都會是你指定的顏色
print(Style.RESET_ALL)
init()接受一些* * kwargs覆蓋缺省行爲,dom
autoreset是自動恢復到默認顏色字體
init(autoreset = False):
init(wrap=True):The default behaviour is to convert if on Windows and output is to a tty (terminal). spa
在windows系統終端輸出顏色要使用init(wrap=True)3d
#!/usr/bin/env python #encoding: utf-8 from colorama import init, Fore, Back, Style if __name__ == "__main__": init(autoreset=True) # 初始化,而且設置顏色設置自動恢復 print(Fore.RED + 'some red text') print(Back.GREEN + 'and with a green background') print(Style.DIM + 'and in dim text') # 若是未設置autoreset=True,須要使用以下代碼重置終端顏色爲初始設置 #print(Fore.RESET + Back.RESET + Style.RESET_ALL) autoreset=True print('back to normal now')
輸出結果orm

import sys import os import random import string from colorama import Fore,Style,init import platform def print_arg(arg): """ 打印參數 :param arg: :return: """ for ind, val in enumerate(arg): if ind == 0: print_color(Fore.YELLOW,r"------執行%s輸入參數爲--------"% val) else: print(val, end=",") def print_color(color, mes=""): """ 得到系統平臺 windows終端須要設置 init(wrap=True) :param color: :param mes: :return: """ v_system = platform.system() if v_system != 'Windows': print(color+mes) else: # init(wrap=True) print(color+mes) # 得到系統參數 v_arg = sys.argv init(autoreset=True) # 初始化,而且設置顏色設置自動恢復 # print_color(Fore.YELLOW+platform.system()) if len(v_arg) != 4: # print(platform.system()) print_arg(v_arg) print_color(Fore.RED,"---參數輸入錯誤--") print_color(Fore.RED, "fileStrReplace.py 文件名 舊字符串 新字符串") else: f_name = v_arg[1].strip() old_str = v_arg[2].strip() # 舊字符 new_str = v_arg[3].strip() # 替換的新字符 f_new_name = "%s.new" % f_name replace_count = 0 # 字符替換次數 if not os.path.exists(f_name): print_color(Fore.YELLOW, "%s文件不存在" % f_name) else: f_new = open(f_new_name, 'w') f = open(f_name, "r",) for line in f: # 讀取大文件 if old_str in line: new_line = line.replace(old_str, new_str) # 字符替換 replace_count += 1 else: new_line = line f_new.write(new_line) # 內容寫新文件 f.close() f_new.close() if replace_count == 0: print_color(Fore.YELLOW,"字符%s不存在" % (old_str)) else: bak_f = f_name + ''.join(random.sample(string.digits, 6)) os.rename(f_name, bak_f) # 備份舊文件 os.rename(f_new_name, f_name) # 把新文件名字改爲原文件的名字,就把以前的覆蓋掉了 print_color(Fore.GREEN, "文件替換成功,[字符%s替換%s]共%s次,源文件備份[%s]" % (old_str,new_str, replace_count,bak_f)) # print_color(Style.RESET_ALL) # 還原默認顏色