Python:如何使用Click.secho仅设置特定颜色的一个单词

问题描述 投票:0回答:3

我正在使用点击模块。

pip install click

这给了我红色文字

import click
click.secho('Error: This error is ...xx', fg='red')

现在我希望只有'错误:'显示为红色。我怎么能用click.secho做到这一点?

python click
3个回答
4
投票

来自clickecho method文档

除此之外,如果安装了colorama,echo函数也将支持巧妙处理ANSI代码。

来自colorama文档

print('\033[31m' + 'some red text')
print('\033[30m') # and reset to default color

因此,结合起来,你应该有类似的东西

click.echo('\033[31m' + 'Error:' + '\033[30m' + ' This error ... ')

得到你想要的东西。


3
投票

使用click.echoclick.style

click.echo(click.style("Error", fg="red") + ": This error is...")

1
投票

您可以使用内置的secho命令和nl(换行)标志。

在您的特定用例中,它看起来像

click.secho('Error', fg='red', nl=False) # This will prevent the secho statement from starting a new line
click.echo(': This error is ...xx')

这将为您提供所需的输出

© www.soinside.com 2019 - 2024. All rights reserved.