Skip to content
Myr

utils.rst

This file

Path

docs/utils.rst

74 lines · 2.4 KiB

Last changed by

Added filename format functionArmin Ronacherbefore adoption31043c3

History of this file

Take it

1Utilities2=========34.. currentmodule:: click56Besides the functionality that click provides to interface with argument7parsing and handling, it also provides a bunch of addon functionality that8is useful for writing command line utilities.91011Printing to Stdout12------------------1314The most obvious helper is the :func:`echo` function which in many ways15works like the Python print statement or function.  The main difference is16that it works the same on Python 2 and 3 and it intelligently detects17misconfigured output streams and will never fail (except on Python 3, for18more information see :ref:`python3-limitations`).1920Example::2122    import click2324    click.echo('Hello World!')2526Most importantly it can print both unicode and binary data, unlike the27builtin ``print`` function on Python 3 which cannot output any bytes.  It28will however emit a trailing newline by default which needs to be29supressed by passing ``nl=False``::3031    click.echo(b'\xe2\x98\x83', nl=False)323334Printing Filenames35------------------3637Because filenames might not be unicode formatting them can be a bit38tricky.  Generally this is easier on Python 2 than 3 as you can just write39the bytes to stdout with the print function, but at least on Python 3 you40will need to always operate in unicode.4142The way this works with click is through the :func:`format_filename`43function.  It does a best effort conversion of the filename to Unicode and44will never fail.  This makes it possible to use these filenames in the45context of a full unicode string.4647Example::4849    click.echo('Path: %s' % click.format_filename(b'foo.txt'))505152Standard Streams53----------------5455For command line utilities it's very important to get access to input and56output streams reliably.  Python generally provides access to these57streams through ``sys.stdout`` and friends, but unfortunately there are58API differences between 2.x and 3.x.  Especially in regards to how these59streams respond to unicode and binary data there are wide differences.6061Because of this click provides the :func:`get_binary_stream` and62:func:`get_text_stream` which produce consistent results with different63Python versions and for widely misconfigured terminals.6465The end result is that these functions will always return a functional66stream object (except in very odd cases on Python 3, see67:ref:`python3-limitations`).6869Example::7071    import click7273    stdin_text = click.get_text_stream('stdin')74    stdout_binary = click.get_binary_stream('stdout')