Skip to content
Myr

utils.rst

This file

Path

docs/utils.rst

368 lines · 11.3 KiB

Last changed by

Added err to click echo docsArmin Ronacherbefore adoption1b3a822

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 in Python 2 and 3, it intelligently detects17misconfigured output streams, and it will never fail (except in 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 the27built-in ``print`` function in Python 3, which cannot output any bytes.  It28will, however, emit a trailing newline by default, which needs to be29suppressed by passing ``nl=False``::3031    click.echo(b'\xe2\x98\x83', nl=False)3233.. versionadded:: 3.03435Starting with Click 3.0 you can also easily print to standard error by36passing ``err=True``::3738    click.echo('Hello World!', err=True)394041.. _ansi-colors:4243ANSI Colors44-----------4546.. versionadded:: 2.04748Starting with Click 2.0, the :func:`echo` function gained extra49functionality to deal with ANSI colors and styles.  Note that on Windows,50this functionality is only available if `colorama`_ is installed.  If it51is installed, then ANSI codes are intelligently handled.5253Primarily this means that:5455-   Click's :func:`echo` function will automatically strip ANSI color codes56    if the stream is not connected to a terminal.57-   the :func:`echo` function will transparently connect to the terminal on58    Windows and translate ANSI codes to terminal API calls.  This means59    that colors will work on Windows the same way they do on other60    operating systems.6162Note for `colorama` support: Click will automatically detect when `colorama`63is available and use it.  Do *not* call ``colorama.init()``!6465To install `colorama`, run this command::6667    $ pip install colorama6869For styling a string, the :func:`style` function can be used::7071    import click7273    click.echo(click.style('Hello World!', fg='green'))74    click.echo(click.style('Some more text', bg='blue', fg='white'))75    click.echo(click.style('ATTENTION', blink=True, bold=True))7677The combination of :func:`echo` and :func:`style` is also available in78a single function called :func:`secho`::7980    click.secho('Hello World!', fg='green')81    click.secho('Some more text', bg='blue', fg='white')82    click.secho('ATTENTION', blink=True, bold=True)838485.. _colorama: https://pypi.python.org/pypi/colorama8687Pager Support88-------------8990In some situations, you might want to show long texts on the terminal and91let a user scroll through it.  This can be achieved by using the92:func:`echo_via_pager` function which works similarly to the :func:`echo`93function, but always writes to stdout and, if possible, through a pager.9495Example:9697.. click:example::9899    @click.command()100    def less():101        click.echo_via_pager('\n'.join('Line %d' % idx102                                       for idx in range(200)))103104105Screen Clearing106---------------107108.. versionadded:: 2.0109110To clear the terminal screen, you can use the :func:`clear` function that111is provided starting with Click 2.0.  It does what the name suggests: it112clears the entire visible screen in a platform-agnostic way:113114::115116    import click117    click.clear()118119120Getting Characters from Terminal121--------------------------------122123.. versionadded:: 2.0124125Normally, when reading input from the terminal, you would read from126standard input.  However, this is buffered input and will not show up until127the line has been terminated.  In certain circumstances, you might not want128to do that and instead read individual characters as they are being written.129130For this, Click provides the :func:`getchar` function which reads a single131character from the terminal buffer and returns it as a Unicode character.132133Note that this function will always read from the terminal, even if stdin134is instead a pipe.135136Example::137138    import click139140    click.echo('Continue? [yn] ', nl=False)141    c = click.getchar()142    click.echo()143    if c == 'y':144        click.echo('We will go on')145    elif c == 'n':146        click.echo('Abort!')147    else:148        click.echo('Invalid input :(')149150Note that this reads raw input, which means that things like arrow keys151will show up in the platform's native escape format.  The only characters152translated are ``^C`` and ``^D`` which are converted into keyboard153interrupts and end of file exceptions respectively.  This is done because154otherwise, it's too easy to forget about that and to create scripts that155cannot be properly exited.156157158Waiting for Key Press159---------------------160161.. versionadded:: 2.0162163Sometimes, it's useful to pause until the user presses any key on the164keyboard.  This is especially useful on Windows where ``cmd.exe`` will165close the window at the end of the command execution by default, instead166of waiting.167168In click, this can be accomplished with the :func:`pause` function.  This169function will print a quick message to the terminal (which can be170customized) and wait for the user to press a key.  In addition to that,171it will also become a NOP (no operation instruction) if the script is not172run interactively.173174Example::175176    import click177    click.pause()178179180Launching Editors181-----------------182183.. versionadded:: 2.0184185Click supports launching editors automatically through :func:`edit`.  This186is very useful for asking users for multi-line input.  It will187automatically open the user's defined editor or fall back to a sensible188default.  If the user closes the editor without saving, the return value189will be `None` otherwise the entered text.190191Example usage::192193    import click194195    def get_commit_message():196        MARKER = '# Everything below is ignored\n'197        message = click.edit('\n\n' + MARKER)198        if message is not None:199            return message.split(MARKER, 1)[0].rstrip('\n')200201Alternatively, the function can also be used to launch editors for files by202a specific filename.  In this case, the return value is always `None`.203204Example usage::205206    import click207    click.edit(filename='/etc/passwd')208209210Launching Applications211----------------------212213.. versionadded:: 2.0214215Click supports launching applications through :func:`launch`.  This can be216used to open the default application assocated with a URL or filetype.217This can be used to launch web browsers or picture viewers, for instance.218In addition to this, it can also launch the file manager and automatically219select the provided file.220221Example usage::222223    click.launch('http://click.pocoo.org/')224    click.launch('/my/downloaded/file.txt', locate=True)225226227Printing Filenames228------------------229230Because filenames might not be Unicode, formatting them can be a bit231tricky.  Generally, this is easier in Python 2 than on 3, as you can just232write the bytes to stdout with the ``print`` function, but in Python 3, you233will always need to operate in Unicode.234235The way this works with click is through the :func:`format_filename`236function.  It does a best-effort conversion of the filename to Unicode and237will never fail.  This makes it possible to use these filenames in the238context of a full Unicode string.239240Example::241242    click.echo('Path: %s' % click.format_filename(b'foo.txt'))243244245Standard Streams246----------------247248For command line utilities, it's very important to get access to input and249output streams reliably.  Python generally provides access to these250streams through ``sys.stdout`` and friends, but unfortunately, there are251API differences between 2.x and 3.x, especially with regards to how these252streams respond to Unicode and binary data.253254Because of this, click provides the :func:`get_binary_stream` and255:func:`get_text_stream` functions, which produce consistent results with256different Python versions and for a wide variety pf terminal configurations.257258The end result is that these functions will always return a functional259stream object (except in very odd cases in Python 3; see260:ref:`python3-limitations`).261262Example::263264    import click265266    stdin_text = click.get_text_stream('stdin')267    stdout_binary = click.get_binary_stream('stdout')268269270Intelligent File Opening271------------------------272273.. versionadded:: 3.0274275Starting with Click 3.0 the logic for opening files from the :class:`File`276type is exposed through the :func:`open_file` function.  It can277intelligently open stdin/stdout as well as any other file.278279Example::280281    import click282283    stdout = click.open_file('-', 'w')284    test_file = click.open_file('test.txt', 'w')285286If stdin or stdout are returned, the return value is wrapped in a special287file where the context manager will prevent the closing of the file.  This288makes the handling of standard streams transparent and you can always use289it like this::290291    with click.open_file(filename, 'w') as f:292        f.write('Hello World!\n')293294295Finding Application Folders296---------------------------297298.. versionadded:: 2.0299300Very often, you want to open a configuration file that belongs to your301application.  However, different operating systems store these configuration302files in different locations depending on their standards.  Click provides303a :func:`get_app_dir` function which returns the most appropriate location304for per-user config files for your application depending on the OS.305306Example usage::307308    import os309    import click310    import ConfigParser311312    APP_NAME = 'My Application'313314    def read_config():315        cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini')316        parser = ConfigParser.RawConfigParser()317        parser.read([cfg])318        rv = {}319        for section in parser.sections():320            for key, value in parser.items(section):321                rv['%s.%s' % (section, key)] = value322        return rv323324325Showing Progress Bars326---------------------327328.. versionadded:: 2.0329330Sometimes, you have command line scripts that need to process a lot of data,331but you want to quickly show the user some progress about how long that332will take.  Click supports simple progress bar rendering for that through333the :func:`progressbar` function.334335The basic usage is very simple: the idea is that you have an iterable that336you want to operate on.  For each item in the iterable it might take some337time to do processing.  So say you have a loop like this::338339    for user in all_the_users_to_process:340        modify_the_user(user)341342To hook this up with an automatically updating progress bar, all you need343to do is to change the code to this::344345    import click346347    with click.progressbar(all_the_users_to_process) as bar:348        for user in bar:349            modify_the_user(user)350351Click will then automatically print a progress bar to the terminal and352calculate the remaining time for you.  The calculation of remaining time353requires that the iterable has a length.  If it does not have a length354but you know the length, you can explicitly provide it::355356    with click.progressbar(all_the_users_to_process,357                           length=number_of_users) as bar:358        for user in bar:359            modify_the_user(user)360361Another useful feature is to associate a label with the progress bar which362will be shown preceding the progress bar::363364    with click.progressbar(all_the_users_to_process,365                           label='Modifying user accounts',366                           length=number_of_users) as bar:367        for user in bar:368            modify_the_user(user)