pycharm支持\033, CMD不支持, 所以我們需要引入colorama
如果直接調(diào)用init()方法, pycharm的控制臺不會有顏色, CMD中有顏色, 故引入ctypes判斷是在CMD中還是在python IDE中
具體代碼如下:
from ctypes import *
from colorama import init, Fore, Style
hwnd = windll.user32.GetForegroundWindow()
out = windll.kernel32.GetStdHandle(-0xb) # stdin: 0xa, stdout: 0xb, stderr: 0xc
rtn = windll.kernel32.SetConsoleTextAttribute(out, 0x7)
if rtn:
# autoreset:是否自動清除格式, 設為True之后,CMD可以生效,但pycharm設置不上,會導致兩邊效果不一致
init()
print("hello,world!")
print(Fore.RED + "hello,world!" + Style.RESET_ALL)
print("hello,world!")