Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set only one word in a specific color using Click.secho

Tags:

python

click

I'm using the click module.

pip install click

This gives me red text

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

Now I want that only 'Error:' is shown in red. How can I do this using click.secho?

like image 785
DenCowboy Avatar asked Mar 09 '18 12:03

DenCowboy


3 Answers

Use click.echo with click.style

click.echo(click.style("Error", fg="red") + ": This error is...")
like image 66
0xDEC0DE Avatar answered Sep 26 '22 21:09

0xDEC0DE


You can use the built in secho command with the nl (new line) flag.

In your specific use case it would look like

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

This will give you the output you wanted

like image 44
bluesummers Avatar answered Sep 23 '22 21:09

bluesummers


From click documentation for the echo method

In addition to that, if colorama is installed, the echo function will also support clever handling of ANSI codes.

From colorama documentation

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

Thus, combining, you should have something like the following

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

to get what you were looking for.

like image 38
Ignacio Vergara Kausel Avatar answered Sep 25 '22 21:09

Ignacio Vergara Kausel