pythonpython-click

How to force Python Click to emit colors when writing to a pipe?


When click.secho("helo", fg="yellow") writes to a pipe, the colors are stripped by default. If there a way to force click to emit the color codes even when stdout is a pipe?

Motivation: We have a Python program that dispatches a scons script, reads its stdout pipe and write it to a terminal. We would like to see on the terminal the color information from click.secho(...) statements in the scons script. If needed, we can add at the beginning of the scons script a call to click to force color preservation.


Solution

  • click.echo specifically removes color and style codes if the output doesn't look like a terminal, and click.secho is just a wrapper around click.echo and click.style.

    You can pass color=True to unconditionally preserve color/style codes:

    click.secho("helo", fg="yellow", color=True)