簡介
Python的Colorama模塊,可以跨多終端,顯示字體不同的顏色和背景,只需要導入colorama模塊即可,不用再每次都像linux一樣指定顏色。
1. 安裝colorama模塊
pip install colorama
2. 常用格式常數
Fore是針對字體顏色,Back是針對字體背景顏色,Style是針對字體格式
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都需要大寫,先指定是顏色和樣式是針對字體還是字體背景,然后再添加顏色,顏色就是英文單詞指定的顏色
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')
輸出結果

# 記得要及時關閉colorma的作用范圍
# 如果不關閉的話,后面所有的輸出都會是你指定的顏色
print(Style.RESET_ALL)
3.Init關鍵字參數:
init()接受一些* * kwargs覆蓋缺省行為,
autoreset是自動恢復到默認顏色
init(autoreset = False):
init(wrap=True):The default behaviour is to convert if on Windows and output is to a tty (terminal).
在windows系統終端輸出顏色要使用init(wrap=True)
#!/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')
輸出結果


4.使用實例
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) # 還原默認顏色
