【基于他人成果改进】Python 彩色文本输出(Pycharm和CMD中的效果一样)(从本人简书博客移入)

pycharm支持\033, CMD不支持, 所以我们需要引入colorama
如果直接调用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!")

猜你喜欢

转载自blog.csdn.net/guggle15/article/details/120000876
今日推荐