summaryrefslogtreecommitdiff
path: root/docs/utils.rst
blob: 251d61b773f3254cddfeeebf55000c48dc9a5466 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
Utilities
=========

.. currentmodule:: click

Besides the functionality that click provides to interface with argument
parsing and handling, it also provides a bunch of addon functionality that
is useful for writing command line utilities.


Priting to Stdout
-----------------

The most obvious helper is the :func:`echo` function which in many ways
works like the Python print statement or function.  The main difference is
that it works the same on Python 2 and 3 and it intelligently detects
misconfigured output streams and will never fail (except on Python 3, for
more information see :ref:`python3-limitations`).

Example::

    import click

    click.echo('Hello World!')

Most importantly it can print both unicode and binary data, unlike the
builtin ``print`` function on Python 3 which cannot output any bytes.  It
will however emit a trailing newline by default which needs to be
supressed by passing ``nl=False``::

    click.echo(b'\xe2\x98\x83', nl=False)


Standard Streams
----------------

For command line utilities it's very important to get access to input and
output streams reliably.  Python generally provides access to these
streams through ``sys.stdout`` and friends, but unfortunately there are
API differences between 2.x and 3.x.  Especially in regards to how these
streams respond to unicode and binary data there are wide differences.

Because of this click provides the :func:`get_binary_stream` and
:func:`get_text_stream` which produce consistent results with different
Python versions and for widely misconfigured terminals.

The end result is that these functions will always return a functional
stream object (except in very odd cases on Python 3, see
:ref:`python3-limitations`).

Example::

    import click

    stdin_text = click.get_text_stream('stdin')
    stdout_binary = click.get_binary_stream('stdout')