Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between print and click.echo in Python 3?

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?

like image 635
Herman Stashinskii Avatar asked Apr 18 '18 18:04

Herman Stashinskii


People also ask

What is click echo in Python?

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.

What is difference with print and in Python?

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.

How do you use the click function in Python?

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.

How do you define print in Python?

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.


Video Answer


1 Answers

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.

like image 141
Zalatik Avatar answered Sep 30 '22 17:09

Zalatik