click Documentation

Python composable command line interface toolkit

17,617 stars Python Python 1 file ยท ~6,064 tokens #cli#click#pallets#python
RAW Doc

1. Project Overview & Quickstart (pallets/click)

Click

Click is a Python package for creating beautiful command line interfaces
in a composable way with as little code as necessary. It's the "Command
Line Interface Creation Kit". It's highly configurable but comes with
sensible defaults out of the box.

It aims to make the process of writing command line tools quick and fun
while also preventing any frustration caused by the inability to
implement an intended CLI API.

Click in three points:

  • Arbitrary nesting of commands
  • Automatic help page generation
  • Supports lazy loading of subcommands at runtime

A Simple Example

python
import click

@click.command()
@click.option("--count", default=1, help="Number of greetings.")
@click.option("--name", prompt="Your name", help="The person to greet.")
def hello(count, name):
    """Simple program that greets NAME for a total of COUNT times."""
    for _ in range(count):
        click.echo(f"Hello, {name}!")

if __name__ == '__main__':
    hello()
text
$ python hello.py --count=3
Your name: Click
Hello, Click!
Hello, Click!
Hello, Click!

The Pallets organization develops and supports Click and other popular
packages. In order to grow the community of contributors and users, and
allow the maintainers to devote more time to the projects, please
donate today
.

Contributing

See our detailed contributing documentation for many ways to
contribute, including reporting issues, requesting features, asking or answering
questions, and making PRs.

2. Official Technical Reference & Guides (pallets/website)

File: README.md

Pallets Projects Website

This is the code and content for https://palletsprojects.com. Static content
from the content folder is loaded when the server is started then served
quickly from memory or cache. This allows editing content as plain files like a
static site, while also taking advantage of Python and a full application.


File: content/blog/pycon-2018-click/index.md

toml
title = "PyCon and Adding Maintainers to Click"
author_name = "David Lord"
published = 2018-06-01
tags = ["meta"]

In May I attended PyCon US 2018 in Cleveland, Ohio. It's a great opportunity to
meet people interested in the Pallets projects and Python web applications. It
can be a little intimidating, but also a lot of fun. The biggest difficulty is
that there are too many things to do, and I always wish everyone could have a
few more days together.

During the main conference, while talks are happening, anyone can organize "open
spaces," impromptu meetings for any topic. I organized a Pallets open space, and
we had a huge turnout. I was kind of unprepared for the size, so we started with
people asking me questions, and then split up into tables for new users, Flask,
Click, and Jinja.

For up to four days after the talks, developers get together for sprints,
working together to contribute to Python open source projects. Experienced
developers help new ones learn how to contribute, and everyone gets to learn
about new projects and meet the developers behind them.

At the open space, I had mentioned that no one had really been maintaining Click
for the past year. It turns out a lot of people use Click. They came motivated
from the open space to contribute during the sprint. Some were new to
contributing, but they all had one thing in common: they knew how Click was
being used more than I did! So I took a chance and gave them all write
permissions to the repository. Click started at ~250 open issues and 68 pull
requests. After 2 days, it was at 140 issues and 22 pull requests. Wow! With
that success, I'm officially welcoming all these new maintainers to the Pallets
Click team. While Click stole the show, we had great contributions to Werkzeug,
Flask, and Jinja as well.

If you want to get involved, a great way is to
watch our repositories on GitHub.
You'll get notifications for each issue, so you can see what's happening and
start contributing. You can help by triaging issues, improving tests and
documentation, and fixing bugs. If your company uses a Pallets project like
Flask, Click, or Jinja, consider pointing them to our
PSF donation page. Donations will help get maintainers to more
events so we can do more sprints like this one. Thank you to everyone at PyCon
and in the community for making Pallets a success!


File: content/blog/blinker-1-6-released.md

toml
title = "Blinker 1.6 Released"
author_name = "P G Jones"
published = 2023-04-02
tags = ["releases"]

Signalling allows for applications to be decoupled by allowing designated
receivers to be informed when an action has taken place (the signal). Flask and
Quart both utilise the excellent Blinker
library to support signals, and it is version 1.6 of this library that has been
released.

This is the second major release of Blinker since maintenance transferred to the
Pallets-eco organisation, and represents a desire to
maintain it for the benefit of Flask, Quart, and indeed Blinker users.

The Changelog for 1.6 is
headlined by a mondernisation of the project structure which should ensure
easier maintenance into the years to come. In addition, we've added:

  • an ability to temporarily mute signals,
  • support for int senders,
  • support for async (coroutine) receivers,
  • and we've type hinted the project.

File: content/blog/click-7-0-released.md

toml
title = "Click 7.0 Released"
author_name = "David Lord"
published = 2018-09-25
tags = ["releases"]

The Pallets team is pleased to release Click 7.0. Thank you to everyone who contributed
online and in person at the PyCon US 2018 sprint! With the help of the community as well
as some new maintainers, we've managed to resolve hundreds of long standing issues and
pull requests.

Due to the length of time since the last release, there are a significant number of new
features and
fixes. Check out the changelog
for a list of all code changes and links to the relevant issues. Changes include:

  • Shell autocompletion has improved in a number of areas.
    • Native ZSH completion was added, and supports its enhanced parameter
      documentation.
    • The choice type can be completed.
    • Completion correctly handles chained commands, spaces, defaults, and partial
      completions.
    • Parameters can provide a callback to customize completion.
  • On Windows click.echo can now output more than 16k characters in one call. On
    Windows 7, a 64k limit on binary stream output is also worked around.
  • click.getchar returns Unicode on Windows.
  • When piping input and output, more cases of closed pipes are detected and handled
    instead of raising errors.
  • The CliRunner used for testing separates stdout and stderr.
  • New DateTime and FloatRange parameter types.
  • Flags to mark a parameter as hidden or deprecated.
  • Numerous improvements and fixes to i/o, help, parameters, and testing.

Read the Docs

Click is the first Pallets project to move its docs to Read the Docs. Our projects
currently use a custom builder and hosting, but this became too difficult with limited
maintainer time. Thank you to everyone at RTD who helped with the transition!

The new URL for the docs is https://click.palletsprojects.com/. The
old https://click.palletsprojects.com/ domain will redirect to the new one while we
continue to migrate, but will eventually go away. Please use the new URL going forward.

Click's docs use a custom Sphinx theme and extensions. As part of the move, these were
extracted to a separate Python package.
Install Pallets-Sphinx-Themes to use
Click's theme when writing extensions for a more cohesive look.

Install or Upgrade

Install from PyPI with pip:

text
pip install -U Click

Get Involved

Click and the Pallets team depends on you, the community. Whether you report issues,
write documentation, create patches, or answer questions, we appreciate all the help you
provide. Star the project on GitHub to show support,
and watch the
repository to see discussions and pull requests as they happen.

We now accept donations through the Python Software Foundation in order to support our
efforts to maintain the projects and grow the community. **Click here to donate.
**


File: content/blog/click-7-1-released.md

toml
title = "Click 7.1 Released"
author_name = "David Lord"
published = 2020-03-09
tags = ["releases"]

The Pallets team is pleased to release Click 7.1.

Read the full changelog
to understand what may affect your code when upgrading.

  • Drop support for Python 3.4. This will be the last version to
    support Python 2.7 and 3.5.
  • Multiple fixes in low-level Windows compatibility code.
  • Colored output in Jupyter notebooks on Linux and Mac.
  • Updated Bash and ZSH tab completion support. Add support for Fish.
  • Better formatting when option help text contains newlines.

This also fixes a packaging issue from 7.0 where the project name in the
package metadata was changed to "Click" with an upper case "C". This has
been reverted, the name is now correctly reported in all lower case, "click".

Version 8.0 Coming Soon

As outlined in Ending Python 2 Support,
7.1.x will be the last version to support Python 2.7 and 3.5. The next
version will be 8.0 and will support Python 3.6 and newer.

Install or Upgrade

Install from PyPI with pip:

text
pip install -U click

The Pallets organization accepts donations as part of the non-profit
Python Software Foundation (PSF). Donations through the PSF support our
efforts to maintain the projects and grow the community.

Click here to donate. โค


File: content/blog/community-survey-2019.md

toml
title = "Take the Pallets / Flask Community Survey"
author_name = "David Lord"
published = 2019-01-29
tags = ["meta"]

One of my goals as a Pallets maintainer is to build the community around our projects.
The Pallets projects (Flask, Jinja, Click, etc.) are downloaded millions of times each
month, but it's hard to get a clear picture of what our users do and want with downloads
stats only. We'd like to learn about you and your projects. Knowing more about our
community will help us decide what to focus on to grow the Pallets projects.

Click here to take our Community Survey.

Please share the link with friends, coworkers, and the internet! We're looking forward
to seeing everyone's responses! You can follow https://twitter.com/PalletsTeam or this
blog to get updates about Pallets, including the survey results.


File: content/blog/donate.md

toml
title = "Donate to Support Pallets"
author_name = "David Lord"
published = 2018-04-26
tags = ["meta"]

Pallets is excited to announce that we have joined the Python Software
Foundation's Fiscal Sponsorship program. As a non-profit organization,
the PSF will accept donations on behalf of Pallets into a dedicated
account.

Donations enable more attention from maintainers, which translates into
more time devoted to fixing bugs, developing features, and making
quicker releases. Click here to donate today.

The Pallets organization develops and supports Flask, Jinja, Werkzeug,
Click, and other Python libraries. These libraries power applications of
all sizes around the world, and are downloaded millions of times each
month. Despite their popularity, the projects are primarily maintained
by only a few developers. The goal of Pallets is to grow the community
around these projects to create a sustainable group of contributors and
users.

Your donation will help:

  • Allow maintainers to devote more of their time to the projects.
  • Recognize outstanding contributors in the community.
  • Allow maintainers and community members to attend conferences.
  • Acquire infrastructure and developer tools.
  • Sponsor local meetup events.
  • And more!

If you like the work we do, you may donate as an
individual. If your employer uses Flask or any of the Pallets projects,
reach out to them to donate.

Flask and the Pallets team depends on you, the community. We thank you
for all the contributions you've already made, and look forward to
growing the community even more.

Click here to donate today.


File: content/blog/end-python2-prereleases.md

toml
title = "New Flask, Jinja2, Click, Werkzeug, ItsDangerous, and MarkupSafe major release candidates"
author_name = "Philip Jones"
published = 2021-04-29
tags = ["releases"]

The Pallets team is pleased to announce that release candidates are
now available for the next major version of each project.

Check out the changelogs for every project to see what's new:

Please help us prepare for the final release by testing the prerelease
versions and reporting any issues you have. To upgrade to pre-releases
with pip, use the --pre flag, e.g.:

text
pip install -U --pre Flask

These new major versions all drop support for Python 2 and 3.5,
requiring Python 3.6 as the minimum supported version.

Release highlights

These are a few highlights, see the changelogs linked above for the
full release details. More detailed posts about each project's
highlights will be made with the final releases.

  • All projects (Jinja coming soon) now provide type hints.
  • Flask gains limited async/await support.
  • Flask supports nested blueprints.
  • Flask tells the browser to cache static files more intelligently, so
    changes to CSS or images show up immediately.
  • Flask introduces short form route decorators, such as @app.post()
    as a shortcut for @app.route(methods=["POST"]).
  • Click's shell completion system has been rewritten.
  • Click will now prompt for values where they are omitted.
  • Werkzeug now provides send_file and send_from_directory helpers.
  • Werkzeug's test client always returns a Response object.
  • Werkzeug's multipart parsing performance increases by a factor of 15.

Release date

The Pallets team is aiming to release on or before PyCon 2021, i.e. a
target release date of the 11th of May 2021.


File: content/blog/ending-python2-support.md

toml
title = "Ending Python 2 Support"
author_name = "David Lord"
published = 2019-12-17
tags = ["meta"]

Upstream support for Python 2.7 is ending on January 1, 2020.
Pallets is joining the community of open source projects
ending support for Python 2 at that time. Our statement and support plan
are based on PyTest's announcement.

We will be dropping support for Python 2.7 as well as Python 3.5 and
below, as their support windows have ended or will end around the same
time. Future releases of each Pallets project will only support Python
versions still supported upstream, which can be found in the
Python Developer's Guide.

The last version branch of each core project to support Python 2.7
and Python 3.5 are:

  • Flask 1.1.x
  • Werkzeug 1.0.x
  • Click 7.x
  • Jinja 2.11.x
  • ItsDangerous 1.1.x
  • MarkupSafe 1.1.x

Each project will receive a major version bump to indicate support
for only 3.6+:

  • Flask 2.0
  • Werkzeug 2.0
  • Click 8.0
  • Jinja 3.0
  • ItsDangerous 2.0
  • MarkupSafe 2.0

Thanks to the python_requires package metadata, Python 2.7 and
3.5 users with a modern pip version will install the last supported
version automatically even if later versions are available.

The team will no longer backport patches for unsupported versions, but
the branches will continue to exist. The team will be happy to
accept patches contributed by the community for any severe security and
usability issues until mid-2020.

We made this decision based on multiple factors. Foremost is ease of
community contribution and maintainer availability. As time goes on,
fewer contributors have used or are familiar with the differences
between Python 2 and 3. Contributors and maintainers must keep track of
an ever growing list of obscure compatibility issues and workarounds,
and cannot use many modern features.

Over the last two years, we've talked to many developers and teams at
conferences and meetups and heard overwhelming support for the move to
Python 3. This is backed up by data collected from our community in a
survey we ran during January 2019, with 92% of respondents already using
or actively upgrading to Python 3. The PSF developer survey and
PyPI statistics report similar majorities and show adoption continuing
to increase.

Thank you to everyone in the community for your support, and to everyone
who has made this transition a reality. We look forward to continuing
to develop the Pallets projects with you!


File: content/blog/flask-0-11-released.md

toml
title = "Flask 0.11 Released"
author_name = "Armin Ronacher"
published = 2016-05-29
tags = ["releases"]

After a very long, long waiting time Flask finally got a new release. There
really was no good reason that there has not been a release in such a long time
but unfortunately once things are postponed for too long a certain release
anxiety kicks in.

In this case this was long tagged as 1.0 but we decided for renaming it to
0.11 and back out some of the more controversial changes. In particular the
new command line interface for Flask was modified a bit to not depend on some
specific functionality in the supporting Click library.

Highlights of this release are the improved development experience which now
stalls the browser on reload instead of bringing up a "connection reset"
page and the new command line support.

Future Plans

This is also the first Flask release under the new pallets organization and
from now on we hope to bring you releases more frequently. Ideally with the
next release we also update the website to find a new home for the showcase,
flask extension list as well as the snippet section to allow the community to
take care of those things themselves.

Changelog

  • Added support to serializing top-level arrays to flask.jsonify. This
    introduces a security risk in ancient browsers. See
    json-security
    for details.
  • Added before_render_template signal.
  • Added **kwargs to flask.Test.test_client to support passing
    additional keyword arguments to the constructor of
    flask.Flask.test_client_class.
  • Added SESSION_REFRESH_EACH_REQUEST config key that controls the
    set-cookie behavior. If set to True a permanent session will be
    refreshed each request and get their lifetime extended, if set to
    False it will only be modified if the session actually modifies.
    Non permanent sessions are not affected by this and will always
    expire if the browser window closes.
  • Made Flask support custom JSON mimetypes for incoming data.
  • Added support for returning tuples in the form (response, headers)
    from a view function.
  • Added flask.Config.from_json.
  • Added flask.Flask.config_class.
  • Added flask.config.Config.get_namespace.
  • Templates are no longer automatically reloaded outside of debug mode. This
    can be configured with the new TEMPLATES_AUTO_RELOAD config key.
  • Added a workaround for a limitation in Python 3.3's namespace loader.
  • Added support for explicit root paths when using Python 3.3's namespace
    packages.
  • Added the flask command and the flask.cli module to start the local
    debug server through the click CLI system. This is recommended over the old
    flask.run() method as it works faster and more reliable due to a
    different design and also replaces Flask-Script.
  • Error handlers that match specific classes are now checked first,
    thereby allowing catching exceptions that are subclasses of HTTP
    exceptions (in werkzeug.exceptions). This makes it possible
    for an extension author to create exceptions that will by default
    result in the HTTP error of their choosing, but may be caught with
    a custom error handler if desired.
  • Added flask.Config.from_mapping.
  • Flask will now log by default even if debug is disabled. The log format is
    now hardcoded but the default log handling can be disabled through the
    LOGGER_HANDLER_POLICY configuration key.
  • Removed deprecated module functionality.
  • Added the EXPLAIN_TEMPLATE_LOADING config flag which when enabled will
    instruct Flask to explain how it locates templates. This should help
    users debug when the wrong templates are loaded.
  • Enforce blueprint handling in the order they were registered for template
    loading.
  • Ported test suite to py.test.
  • Deprecated request.json in favour of request.get_json().
  • Add "pretty" and "compressed" separators definitions in jsonify() method.
    Reduces JSON response size when JSONIFY_PRETTYPRINT_REGULAR=False by removing
    unnecessary white space included by default after separators.
  • JSON responses are now terminated with a newline character, because it is a
    convention that UNIX text files end with a newline and some clients don't
    deal well when this newline is missing. See
    https://github.com/pallets/flask/pull/1262 -- this came up originally as a
    part of https://github.com/kennethreitz/httpbin/issues/168
  • The automatically provided OPTIONS method is now correctly disabled if
    the user registered an overriding rule with the lowercase-version
    options (issue #1288).
  • flask.json.jsonify
    now supports the datetime.date type (pull request
    #1326).
  • Don't leak exception info of already caught exceptions to context teardown
    handlers (pull request #1393).
  • Allow custom Jinja environment subclasses (pull
    request #1422).
  • flask.g now has pop()
    and setdefault methods.
  • Turn on autoescape for flask.templating.render_template_string by default
    (pull request #1515).
  • flask.ext is now deprecated (pull
    request #1484).
  • send_from_directory
    now raises BadRequest if the filename is invalid on
    the server OS (pull request #1763).
  • Added the JSONIFY_MIMETYPE configuration variable (pull
    request #1728).
  • Exceptions during teardown handling will no longer leave bad application
    contexts lingering around.