python - 打印时更改文本颜色
问题描述
我目前正在设计一个简单的游戏,并且正在尝试更改正在打印的特定事物的颜色。我已经下载了 colorama 模块并使用我在网上找到的示例运行了我的代码,但这不起作用(我稍后会告诉细节)。我知道 Python 选项中的一个设置,但这会影响整个文本而不是特定部分。如果这有助于我的计算机运行 Windows 并且我正在运行 Python 3.8。这是设置代码,然后几行是我在单独文件中的代码。之后的几行是输出:
from setuptools import setup, find_packages
name = 'colorama'
version = '0.1'
def get_long_description(filename):
readme = join(dirname(__file__), filename)
return open(readme).read()
setup(
name=name,
version=version,
description="Cross-platform colored terminal text.",
long_description=get_long_description('README.txt'),
keywords='color colour terminal text ansi windows crossplatform xplatform',
author='Jonathan Hartley',
author_email='tartley@tartley.com',
url='http://code.google.com/p/colorama/',
license='BSD',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=True,
install_requires=[
# -*- Extra requirements: -*-
],
entry_points="""
# -*- Entry points: -*-
""",
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Topic :: Terminals',
]
# see classifiers http://pypi.python.org/pypi?%3Aaction=list_classifiers
)
import colorama
from colorama import Fore, Style
print(Fore.BLUE + "Hello World")
[34mHello World
解决方案
您需要init()
在导入 colorama 之后和打印带有颜色的字符串之前调用某个地方。例如:
import colorama
from colorama import Fore, Style
init()
print(Fore.BLUE + "Hello World")
推荐阅读
- java - PlantUML - 如何将私有方法表示为序列图中的嵌套生命线
- javascript - 如何将多选下拉数据值插入sql表(在一个字段中)
- javascript - GTM 自定义 Javascript 未定义变量
- java - CodeHS:如何在另一个类的 toString 中多次使用一个类的 toString 方法
- excel - VBA - 如何使用 For 循环和 IF 语句使代码更高效?
- java - 如何在 Spring 中复制 MultipartFile?
- python - 熊猫“重新装箱”数据框
- java - Apache spark Row getAs[String]:java.lang.Byte 无法转换为 java.lang.String
- java - 在 GKE 上使用我的应用程序部署 OPA 后容器之间的通信问题
- javascript - 如何隐藏 Google API 密钥并仍然使用它