【问题标题】:Printing text in color in a command window在命令窗口中以彩色打印文本
【发布时间】:2019-12-19 23:03:06
【问题描述】:

我正在编写一个简单的 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()

从下面的截图中,“FAIL”和“PASS”都是绿色的,FAIL应该是红色的,PASS是绿色的。

【问题讨论】:

  • 您是否测试过 coloramablessings 或类似的模块?
  • print(text, end=' ') 在 Python 2 中导致 SyntaxError
  • 对于python 2 做print text, end=' '
  • 同样的错误。请发布一些真实的代码。 -1 到那时。
  • @CristiFati ,我发布的代码是针对 Python 3 的,我添加了针对 python 2 的代码

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


【解决方案1】:

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

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


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

#!/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()

需要注意的几点:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-28
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2016-03-16
    • 1970-01-01
    相关资源
    最近更新 更多