【发布时间】: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是绿色的。
【问题讨论】:
-
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