在命令窗口中以彩色打印文本

时间:2019-12-19 23:03:06

标签: python python-3.x windows python-2.7 ctypes

我正在编写一个简单的python函数,以在命令窗口中的Windows计算机上以彩色方式打印文本。 当我在同一行上打印两个文本时,第一个文本采用第二个的颜色。这在python 3.7中发生,但是在python 2.7中,两个文本可以在同一行上以两种不同的颜色打印。下面是我的代码:

#Python3 code

from ctypes import *

def PrintInColor(text, color):
    # The color is an int and text is simply passed through
    windll.Kernel32.GetStdHandle.restype = c_ulong
    h = windll.Kernel32.GetStdHandle(c_ulong(0xfffffff5))
    x = windll.Kernel32.SetConsoleTextAttribute(h, color)
    print(text, end=' ')

def printing():
    PrintInColor("FAIL", 0xC) #Red  
    PrintInColor("PASS", 0xA) #Green

printing()

Python 2代码

from ctypes import *

def PrintInColor(text, color):
    # The color is an int and text is simply passed through
    windll.Kernel32.GetStdHandle.restype = c_ulong
    h = windll.Kernel32.GetStdHandle(c_ulong(0xfffffff5))
    x = windll.Kernel32.SetConsoleTextAttribute(h, color)
    print text,

def printing():
    PrintInColor("FAIL", 0xC) #Red  
    PrintInColor("PASS", 0xA) #Green

printing()

在下面的屏幕截图中,“失败”和“通过”全部为绿色,失败应为红色,而通过则为绿色。

enter image description here

1 个答案:

答案 0 :(得分:2)

您需要为print使用flush关键字参数。

    print(text, end=' ', flush=True)

enter image description here


除此之外,这是我的测试脚本:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import ctypes

STD_OUTPUT_HANDLE = -11

def raise_if_0(result, func, arguments):
    if result == 0:
        raise Winerror()

_k32 = ctypes.WinDLL('kernel32', use_last_error=True)
_GetStdHandle = _k32.GetStdHandle
_GetStdHandle.restype = ctypes.c_void_p
_GetStdHandle.argtypes = [ctypes.c_void_p]
_SetConsoleTextAttribute = _k32.SetConsoleTextAttribute
_SetConsoleTextAttribute.restype = ctypes.c_bool
_SetConsoleTextAttribute.argtypes = [ctypes.c_void_p, ctypes.c_uint16]
_SetConsoleTextAttribute.errcheck = raise_if_0



def PrintInColor(text, color):
    # The color is an int and text is simply passed through
    hout = _GetStdHandle(ctypes.c_void_p(STD_OUTPUT_HANDLE))
    x = _SetConsoleTextAttribute(hout, color)
    print(text, end=' ', flush=True)

def printing():
    PrintInColor("FAIL", 0xC) #Red  
    PrintInColor("PASS", 0xA) #Green

printing()

一些注意事项:

相关问题