Skip to content
Myr

Make documentation invoke click and fix a bunch of issues

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent 87adb71 · Browse files · 7 files+438 added−150 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+438 added−150 removed

  • other:+438 added−150 removed

7 files+438 added−150 removed

modified:docs/arguments.rst+33 added-24 removed
13 unmodified lines
14The most basic option is a simple string argument of one value. If no15type is provided the type of the default value is used. If no default16value is provided the type is assumed to be :data:`STRING`.1718Example::18Example:1920.. click:example::2122 @click.command()23 @click.argument('filename')24 def touch(filename):25 print(filename)2625And what it looks like::27And what it looks like:2827 $ python touch.py foo.txt28 foo.txt29.. click:run::3031 invoke(touch, args=['foo.txt'])3233Variadic Arguments34------------------3536The second most common version is variadic arguments where a specific (or
3 unmodified lines
4041The value is then passed as a tuple. Note that only one argument really42can be set to ``nargs=-1`` and right now only the last.4341Example::44Example:4546.. click:example::4748 @click.command()49 @click.argument('files', nargs=-1)50 def touch(files):51 for file in files:52 print(file)5349And what it looks like::54And what it looks like:5551 $ python touch.py foo.txt bar.txt52 foo.txt53 bar.txt56.. click:run::5758 invoke(touch, args=['foo.txt', 'bar.txt'])5960.. _file-args:6162File Arguments63--------------
6 unmodified lines
70Click supports this through the :class:`click.File` type which71intelligently handles files for you. It also deals with unicode and bytes72correctly for all versions of Python so your script stays very portable.7369Example::74Example:7576.. click:example::7778 @click.command()79 @click.argument('input', type=click.File('rb'))80 @click.argument('output', type=click.File('wb'))81 def inout(input, output):
2 unmodified lines
84 if not chunk:85 break86 output.write(chunk)8781And what it does::88And what it does:8983 $ python inout.py - hello.txt84 hello85 ^D86 $ python inout.py hello.txt -87 hello90.. click:run::9192 with isolated_filesystem():93 invoke(inout, args=['-', 'hello.txt'], input=['hello'])94 invoke(inout, args=['hello.txt', '-'])9596Environment Variables97---------------------9899Like options, arguments can also get values from an environment variable.100Unlike options however this is only supported for explicitly named101environment variables.10296Example usage::103Example usage:104105.. click:example::106107 @click.command()99 @click.argument('--src', envvar='SRC', type=click.File('r'))108 @click.argument('src', envvar='SRC', type=click.File('r'))109 def echo(src):110 print(src.read())111103 if __name__ == '__main__':104 echo()112And from the command line:113106And from the command line::114.. click:run::115108 $ export SRC=hello.txt109 $ python echo.py110 Hello!116 with isolated_filesystem():117 with open('hello.txt', 'w') as f:118 f.write('Hello World!')119 invoke(echo, env={'SRC': 'hello.txt'})120121In that case it can also be a list of different environment variables122where the first one is picked.123
2 unmodified lines
added:docs/clickdoctools.py+251 added
1import os2import sys3import click4import shutil5import tempfile6import contextlib78try:9 from StringIO import StringIO10except ImportError:11 from io import StringIO1213from docutils import nodes14from docutils.statemachine import ViewList1516from sphinx.domains import Domain17from sphinx.util.compat import Directive181920class EchoingStdin(object):2122 def __init__(self, input, output):23 self._input = input24 self._output = output2526 def __getattr__(self, x):27 return getattr(self._input, x)2829 def read(self, n=-1):30 rv = self._input.read(n)31 self._output.write(rv)32 return rv3334 def readline(self, n=-1):35 rv = self._input.readline(n)36 self._output.write(rv)37 return rv3839 def readlines(self):40 rv = self._input.readlines()41 for line in rv:42 self._output.write(rv)43 return rv4445 def __iter__(self):46 for x in self._input:47 self._output.write(x)48 yield x495051@contextlib.contextmanager52def isolation(input=None, env=None):53 if click.PY2 and isinstance(input, unicode):54 input = input.encode('utf-8')55 input = StringIO(input or '')56 output = StringIO()57 sys.stdin = EchoingStdin(input, output)58 sys.stdin.encoding = 'utf-8'5960 def visible_input(prompt=None):61 sys.stdout.write(prompt or '')62 val = input.readline().rstrip('\r\n')63 sys.stdout.write(val + '\n')64 sys.stdout.flush()65 return val6667 def hidden_input(prompt=None):68 sys.stdout.write((prompt or '') + '\n')69 sys.stdout.flush()70 return input.readline().rstrip('\r\n')7172 sys.stdout = output73 sys.stderr = output74 old_visible_prompt_func = click.visible_prompt_func75 old_hidden_prompt_func = click.hidden_prompt_func76 click.visible_prompt_func = visible_input77 click.hidden_prompt_func = hidden_input7879 old_env = {}80 try:81 if env:82 for key, value in env.iteritems():83 old_env[key] = os.environ.get(value)84 os.environ[key] = value85 yield output86 finally:87 for key, value in old_env.iteritems():88 if value is None:89 try:90 del os.environ[key]91 except Exception:92 pass93 else:94 os.environ[key] = value95 sys.stdout = sys.__stdout__96 sys.stderr = sys.__stderr__97 click.visible_prompt_func = old_visible_prompt_func98 click.hidden_prompt_func = old_hidden_prompt_func99100101@contextlib.contextmanager102def isolated_filesystem():103 cwd = os.getcwd()104 t = tempfile.mkdtemp()105 os.chdir(t)106 try:107 yield108 finally:109 os.chdir(cwd)110 try:111 shutil.rmtree(t)112 except (OSError, IOError):113 pass114115116class ExampleRunner(object):117118 def __init__(self):119 self.namespace = {120 'click': click,121 }122123 def declare(self, source):124 code = compile(source, '<docs>', 'exec')125 eval(code, self.namespace)126127 def run(self, source):128 code = compile(source, '<docs>', 'exec')129 buffer = []130131 def invoke(cmd, args=None, prog_name=None, prog_prefix='python ',132 input=None, env=None, auto_envvar_prefix=None):133 if env:134 for key, value in sorted(env.items()):135 if ' ' in value:136 value = '"%s"' % value137 buffer.append('$ export %s=%s' % (key, value))138 args = args or []139 if prog_name is None:140 prog_name = cmd.name.replace('_', '-') + '.py'141 buffer.append(('$ %s%s %s' % (142 prog_prefix,143 prog_name,144 ' '.join(('"%s"' % x) if ' ' in x else x for x in args)145 )).rstrip())146 if isinstance(input, (tuple, list)):147 input = '\n'.join(input) + '\n'148 with isolation(input=input, env=env) as output:149 try:150 cmd.main(args=args, prog_name=prog_name,151 auto_envvar_prefix=auto_envvar_prefix)152 except SystemExit:153 pass154 buffer.extend(output.getvalue().splitlines())155156 def println(text=''):157 buffer.append(text)158159 eval(code, self.namespace, {160 'invoke': invoke,161 'println': println,162 'isolated_filesystem': isolated_filesystem,163 })164 return buffer165166 def close(self):167 pass168169170def parse_rst(state, content_offset, doc):171 node = nodes.section()172 # hack around title style bookkeeping173 surrounding_title_styles = state.memo.title_styles174 surrounding_section_level = state.memo.section_level175 state.memo.title_styles = []176 state.memo.section_level = 0177 state.nested_parse(doc, content_offset, node, match_titles=1)178 state.memo.title_styles = surrounding_title_styles179 state.memo.section_level = surrounding_section_level180 return node.children181182183def get_example_runner(document):184 runner = getattr(document, 'click_example_runner', None)185 if runner is None:186 runner = document.click_example_runner = ExampleRunner()187 return runner188189190class ExampleDirective(Directive):191 has_content = True192 required_arguments = 0193 optional_arguments = 0194 final_argument_whitespace = False195196 def run(self):197 doc = ViewList()198 runner = get_example_runner(self.state.document)199 try:200 runner.declare('\n'.join(self.content))201 except:202 runner.close()203 raise204 doc.append('.. sourcecode:: python', '')205 doc.append('', '')206 for line in self.content:207 doc.append(' ' + line, '')208 return parse_rst(self.state, self.content_offset, doc)209210211class RunExampleDirective(Directive):212 has_content = True213 required_arguments = 0214 optional_arguments = 0215 final_argument_whitespace = False216217 def run(self):218 doc = ViewList()219 runner = get_example_runner(self.state.document)220 try:221 rv = runner.run('\n'.join(self.content))222 except:223 runner.close()224 raise225 doc.append('.. sourcecode:: text', '')226 doc.append('', '')227 for line in rv:228 doc.append(' ' + line, '')229 return parse_rst(self.state, self.content_offset, doc)230231232class ClickDomain(Domain):233 name = 'click'234 label = 'Click'235 directives = {236 'example': ExampleDirective,237 'run': RunExampleDirective,238 }239240241def delete_example_runner_state(app, doctree):242 runner = getattr(doctree, 'click_example_runner', None)243 if runner is not None:244 runner.close()245 del doctree.click_example_runner246247248def setup(app):249 app.add_domain(ClickDomain)250251 app.connect('doctree-read', delete_example_runner_state)
modified:docs/conf.py+3 added-1 removed
16 unmodified lines
17# add these directories to sys.path here. If the directory is relative to the18# documentation root, use os.path.abspath to make it absolute, like shown here.19sys.path.append(os.path.abspath('_themes'))20sys.path.append(os.path.abspath('..'))21sys.path.append(os.path.abspath('.'))2223# -- General configuration -----------------------------------------------------2425# If your documentation needs a minimal Sphinx version, state it here.26#needs_sphinx = '1.0'2728# Add any Sphinx extension module names here, as strings. They can be extensions29# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.29extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx']30extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx',31 'clickdoctools']3233# Add any paths that contain templates here, relative to this directory.34templates_path = ['_templates']35
184 unmodified lines
modified:docs/index.rst+3 added-1 removed
13 unmodified lines
14- arbitrary nesting of commands15- automatic help page generation16- supports lazy loading of subcommands at runtime1718What does it look like? A simple example can be this::18What does it look like? A simple example can be this:1920.. click:example::2122 import click2324 @click.command()25 @click.option('--count', default=1, help='number of greetings')
44 unmodified lines
modified:docs/options.rst+114 added-99 removed
11 unmodified lines
1213The most basic option is a value option. These options accept one14argument which is a value. If no type is provided the type of the default15value is used. If no default value is provided the type is assumed to be16:data:`STRING`.16:data:`STRING`. The name of the parameter is the longest option defined.1718Example::18.. click:example::1920 @click.command()21 @click.option('--n', default=1)22 def dots(n):23 print('.' * n)2425And on the command line::25And on the command line:2627 $ python dots.py --n=228 ..27.. click:run::2829 invoke(dots, args=['--n=2'])3031In this case the option is of type :data:`INT` because the default value32is an integer.3333The name of the parameter is the longest.3434Multi Value Options35-------------------3637Sometimes you have options that take more than one argument. For options38only a fixed number of arguments is supported. This can be configured by39the ``nargs`` parameter. The values are then stored as a tuple.4042Example::41.. click:example::424443 @click.command()44 @click.option('--pos', nargs=2, type=float)45 def findme(pos):46 print('%s / %s' % pos)4750And on the command line::48And on the command line:4952 $ python findme.py --pos 2.0 3.053 2.0 / 3.050.. click:run::5152 invoke(findme, args=['--pos', '2.0', '3.0'])5354Multiple Options55----------------5657Similar to ``nargs`` there is also the case where sometimes you want to
1 unmodified line
59recorded and not just the last one. For instance ``git commit -m foo -m60bar`` would record two lines for the commit message. ``foo`` and ``bar``.61This can be accomplished with the ``multiple`` flag:6264Example::63Example:6465.. click:example::6667 @click.command()68 @click.option('--message', '-m', multiple=True)69 def commit(message):70 print('\n'.join(message))7171And on the command line::72And on the command line:7373 $ python commit.py -m foo -m bar74 foo75 bar74.. click:run::7576 invoke(commit, args=['-m', 'foo', '-m', 'bar'])7778Counting79--------8081If you have used ``optparse`` or ``argparse`` before you might be missing82support for counting. This is a very rarely useful feature, usually only83useful for implementing verbosity flags. It can however be emulated by83using the multiple flag and taking the length of the end result::84using the multiple flag and taking the length of the end result:8586.. click:example::8788 @click.command()89 @click.option('-v', '--verbose', is_flag=True, multiple=True)90 def log(verbose):91 verbosity = len(verbose)92 print('Verbosity: %s' % verbosity)9391And on the command line::94And on the command line:9593 $ python log.py -vvv94 Verbosity: 396.. click:run::9798 invoke(log, args=['-vvv'])99100Boolean Flags101-------------102103Boolean flags are options that can be enabled or disabled. This can be104accomplished by defining two flags in one go separated by a slash (``/``)105for enabling or disabling the option. Click always wants you to provide106an enable and disable flag so that you can change the default later.107104Example::108Example:109110.. click:example::111112 import os113114 @click.command()115 @click.option('--shout/--no-shout', default=False)
2 unmodified lines
118 if shout:119 rv = rv.upper() + '!!!!111'120 print(rv)121116And on the command line::122And on the command line:123118 $ python info.py --shout119 DARWIN!!!!111120 $ python info.py --no-shout121 Darwin124.. click:run::125126 invoke(info, args=['--shout'])127 invoke(info, args=['--no-shout'])128129If you really don't want an off-switch you can just define one and124manually inform click that something is a flag::130manually inform click that something is a flag:131132.. click:example::133134 import os135136 @click.command()137 @click.option('--shout', is_flag=True)
2 unmodified lines
140 if shout:141 rv = rv.upper() + '!!!!111'142 print(rv)143136And on the command line::144And on the command line:145138 $ python info.py --shout139 DARWIN!!!!111146.. click:run::147148 invoke(info, args=['--shout'])149150Feature Switches151----------------152153In addition to boolean flags there are also feature switches. These are154implemented by setting multiple options to the same parameter name and by155defining a flag value. To set a default flag assign a value of `True` to156the flag that should be the default.157149Example::158.. click:example::159160 import os161162 @click.command()
2 unmodified lines
165 @click.option('--lower', 'transformation', flag_value='lower')166 def info(transformation):167 print(getattr(os.uname()[0], transformation)())168160And on the command line::169And on the command line:170162 $ python info.py --upper163 DARWIN164 $ python info.py --lower165 darwin166 $ python info.py167 DARWIN171.. click:run::172173 invoke(info, args=['--upper'])174 invoke(info, args=['--lower'])175 invoke(info)176177.. _choice-opts:178179Choice Options180--------------
1 unmodified line
182Sometimes you want to have a parameter be a choice of a list of values.183In that case you can use :class:`Choice` type. It can be instanciated184with a list of valid values.185178Example::186Example:187188.. click:example::189190 @click.command()191 @click.option('--hash-type', type=click.Choice(['md5', 'sha1']))192 def digest(hash_type):193 print(hash_type)194185What it looks like::195What it looks like:196187 $ python digest.py --hash-type=md5188 md5197.. click:run::198190 $ python digest.py --hash-type=foo191 Usage: digest.py [OPTIONS]199 invoke(digest, args=['--hash-type=md5'])200 println()201 invoke(digest, args=['--hash-type=foo'])202 println()203 invoke(digest, args=['--help'])204193 Error: Invalid value for hash_type: invalid choice: foo. (choose from md5, sha1)194195 $ python digest.py --help196 Usage: digest.py [OPTIONS]197198 Options:199 --hash-type=[md5|sha1]200 --help Show this message and exit.201205.. _option-prompting:206207Prompting208---------
1 unmodified line
210Sometimes you want parameters that can either be provided from the command211line or if not, you want to ask for user input. This can be implemented212with click by defining a prompt string.213211Example::214Example:215213 import os216.. click:example::217218 @click.command()219 @click.option('--name', prompt=True)220 def hello(name):221 print('Hello %s!' % name)222220And what it looks like::223And what it looks like:224222 $ python hello.py --name=John223 Hello John!224 $ python hello.py225 Name: John226 Hello John!225.. click:run::226227 invoke(hello, args=['--name=John'])228 invoke(hello, input=['John'])229230If you are not happy with the default prompt string you can ask for229a different one::231a different one:232231 import os233.. click:example::234235 @click.command()236 @click.option('--name', prompt='Your name please')237 def hello(name):238 print('Hello %s!' % name)239238What it looks like::240What it looks like:241240 $ python hello.py241 Your name please: John242 Hello John!242.. click:run::243244 invoke(hello, input=['John'])245246Password Prompts247----------------248249Click also supports hidden prompts and asking for confirmation. This is248useful for password input::250useful for password input:251252.. click:example::253254 @click.command()255 @click.option('--password', prompt=True, hide_input=True,256 confirmation_prompt=True)257 def encrypt(password):258 print('Encrypting password to %s' % password.encode('rot13'))259256What it looks like::260What it looks like:261258 $ python encrypt.py259 Password:260 Repeat for confirmation:261 Encrypting password to frpher262.. click:run::263264 invoke(encrypt, input=['secret', 'secret'])265266Because this combination of parameters is quite common this can also be264replaced with the :func:`password_option` decorator::267replaced with the :func:`password_option` decorator:268269.. click:example::270271 @click.command()272 @click.password_option()273 def encrypt(password):274 print('Encrypting password to %s' % password.encode('rot13'))
17 unmodified lines
292:class:`Context` and the value. The context provides some useful features293such as quitting the application and gives access to other already294processed parameters.295291Here an example for a ``--version`` flag::296Here an example for a ``--version`` flag:297298.. click:example::299300 def print_version(ctx, value):301 if not value:302 return303 print('Version 1.0')
8 unmodified lines
312The `expose_value` parameter prevents the now pretty pointless ``version``313parameter to be passed to the callback. If that was not specified a314boolean would be passed to the `hello` script.315309What it looks like::316What it looks like:317311 $ python hello.py 312 Hello World!313 $ python hello.py --version314 Version 1.0318.. click:run::319320 invoke(hello)321 invoke(hello, args=['--version'])322323Yes Parameters324--------------325326For dangerous operations it's very useful to be able to ask a user for327confirmation. This can be done by adding a boolean ``--yes`` flag and328asking for confirmation if the user did not provide it and to fail in a322callback::329callback:330331.. click:example::332333 def abort_if_false(ctx, value):334 if not value:335 ctx.abort()336
3 unmodified lines
340 prompt='Are you sure you want to drop the db?')341 def dropdb():342 print('Dropped all tables!')343335And what it looks like on the command line::344And what it looks like on the command line:345337 $ python dropdb.py338 Are you sure you want to drop the db? [yN]: n 339 Aborted!340 $ python dropdb.py --yes341 Dropped all tables!346.. click:run::347348 invoke(dropdb, input=['n'])349 invoke(dropdb, args=['--yes'])350351Because this combination of parameters is quite common this can also be344replaced with the :func:`confirmation_option` decorator::352replaced with the :func:`confirmation_option` decorator:353354.. click:example::355356 @click.command()357 @click.confirmation_option('Are you sure you want to drop the db?')358 def dropdb():359 print('Dropped all tables!')
15 unmodified lines
375underscore-separated variable in uppercase. So if you have a subcommand376called ``foo`` taking an option called ``bar`` and the prefix is377``MY_TOOL`` then the variable is ``MY_TOOL_FOO_BAR``.378369Example usage::379Example usage:380381.. click:example::382383 @click.command()384 @click.option('--username')385 def greet(username):386 print('Hello %s!' % username)387388 if __name__ == '__main__':389 greet(auto_envvar_prefix='GREETER')390379And from the command line::391And from the command line:392381 $ export GREETER_USERNAME=john382 $ python greet.py383 Hello john!393.. click:run::394395 invoke(greet, env={'GREETER_USERNAME': 'john'},396 auto_envvar_prefix='GREETER')397398The second option is to manually pull values in from specific environment399variables by defining the name of the environment variable on the option.400388Example usage::401Example usage:402403.. click:example::404405 @click.command()406 @click.option('--username', envvar='USERNAME')407 def greet(username):408 print('Hello %s!' % username)409410 if __name__ == '__main__':411 greet()412398And from the command line::413And from the command line:414400 $ export USERNAME=john401 $ python greet.py402 Hello john!415.. click:run::416417 invoke(greet, env={'USERNAME': 'john'})418419In that case it can also be a list of different environment variables420where the first one is picked.
modified:docs/quickstart.rst+24 added-22 removed
14 unmodified lines
15for high-level usage.1617A function becomes a click command line tool by decorating it through18:func:`click.command`. In the most simple version just decorating a19function with this decorator will make it into a callable script::19function with this decorator will make it into a callable script:2021.. click:example::2223 import click2425 @click.command()26 def hello():
4 unmodified lines
3132 if __name__ == '__main__':33 hello()3435And what it looks like:3637.. click:run::3839 invoke(hello, args=[])4041And the corresponding help page:4243.. click:run::4445 invoke(hello, args=['--help'])4647Nesting Commands48----------------4950Commands can be attached to other commands of type :class:`Group`. This51allows arbitrary nesting of scripts. As an example here is a script that38implements two commands for managing databases::52implements two commands for managing databases:5340 import click54.. click:example::5556 @click.group()57 def cli():58 pass
8 unmodified lines
6768 cli.add_command(initdb)69 cli.add_command(dropdb)7057 if __name__ == '__main__':58 cli()5971As you can see the :func:`group` decorator works like the :func:`command`72decorator but creates a :class:`Group` object instead which can be given73multiple subcommands that can be attached with74:meth:`Group.add_command`.7576For simple scripts it's also possible to automatically attach and create a77command by using the :meth:`Group.command` decorator instead. The above67script can be written like this then::78script can be written like this then:7969 import click80.. click:example::8182 @click.group()83 def cli():84 pass
5 unmodified lines
90 @cli.command()91 def dropdb():92 print('Dropped the database')9383 if __name__ == '__main__':84 cli()8594Adding Parameters95-----------------9689To add parameters the :func:`option` and :func:`argument` decorators::97To add parameters the :func:`option` and :func:`argument` decorators:9891 import click99.. click:example::100101 @click.command()102 @click.option('--count', default=1, help='number of greetings')103 @click.argument('name')104 def hello(count, name):105 for x in range(count):106 print('Hello %s!' % name)107100 if __name__ == '__main__':101 hello()108What it looks like:109103What it looks like::110.. click:run::111105 $ python hello.py106 Usage: hello.py [OPTIONS] NAME107108 Options:109 --count=COUNT number of greetings110 --help Show this message and exit.112 invoke(hello, args=['--help'])
modified:click.py+10 added-3 removed
105 unmodified lines
106 pass107 return wrapper108109110# The prompt functions to use. The doc tools currently override these111# functions to customize them.112hidden_prompt_func = getpass.getpass113visible_prompt_func = raw_input114115116class TextWrapper(textwrap.TextWrapper):117118 def _cutdown(self, ucstr, space_left):119 l = 0
47 unmodified lines
167 if file is None:168 file = sys.stdout169 if message:170 if PY2 and isinstance(message, text_type):165 message = message.encode(file.encoding)171 message = message.encode(getattr(file, 'encoding', None)172 or 'utf-8', 'replace')173 file.write(message)174 file.write('\n')175 file.flush()176
1387 unmodified lines
1564 """1565 prompt = '%s [%s]: ' % (text, default and 'Yn' or 'yN')1566 while 1:1567 try:1561 value = raw_input(prompt).lower().strip()1568 value = visible_prompt_func(prompt).lower().strip()1569 except (KeyboardInterrupt, EOFError):1570 raise Abort()1571 if value in ('y', 'yes'):1572 rv = True
32 unmodified lines
1605 """1606 result = None16071608 def prompt_func(text):1602 f = hide_input and getpass.getpass or raw_input1609 f = hide_input and hidden_prompt_func or visible_prompt_func1610 try:1611 return f(text)1612 except (KeyboardInterrupt, EOFError):1613 raise Abort()
50 unmodified lines