I am creating CLI app for Unix terminal using click module. So I see two ways how I can display data:
print(data)
and click.echo(data)
What is difference between them and what should I use?
Click's echo() function will automatically strip ANSI color codes if the stream is not connected to a terminal. the echo() function will transparently connect to the terminal on Windows and translate ANSI codes to terminal API calls.
The only difference here is str1 is a single object and in the second print there are multiple objects (The first argument of print function is *objects) it can take as many positional arguments as we give.
Python click option namesClick derives the name of the option from the long name, if both are used. In the example, we create an option with both short and long names. The name of the variable passed to the function is string , derived from the longer option name. We run the program using both option names.
Definition and UsageThe print() function prints the specified message to the screen, or other standard output device. The message can be a string, or any other object, the object will be converted into a string before written to the screen.
Please, read at least quickstart of library before using it. The answer is in the third part of quickstart.
If you use click click.echo()
is preferred because:
Click attempts to support both Python 2 and Python 3 the same way and to be very robust even when the environment is misconfigured. Click wants to be functional at least on a basic level even if everything is completely broken.
What this means is that the echo() function applies some error correction in case the terminal is misconfigured instead of dying with an UnicodeError.
As an added benefit, starting with Click 2.0, the echo function also has good support for ANSI colors. It will automatically strip ANSI codes if the output stream is a file and if colorama is supported, ANSI colors will also work on Windows. See ANSI Colors for more information.
If you don’t need this, you can also use the print() construct / function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With