comparison venv/lib/python2.7/site-packages/click/termui.py @ 0:d67268158946 draft

planemo upload commit a3f181f5f126803c654b3a66dd4e83a48f7e203b
author bcclaywell
date Mon, 12 Oct 2015 17:43:33 -0400
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:d67268158946
1 import os
2 import sys
3 import struct
4
5 from ._compat import raw_input, text_type, string_types, \
6 isatty, strip_ansi, get_winterm_size, DEFAULT_COLUMNS, WIN
7 from .utils import echo
8 from .exceptions import Abort, UsageError
9 from .types import convert_type
10 from .globals import resolve_color_default
11
12
13 # The prompt functions to use. The doc tools currently override these
14 # functions to customize how they work.
15 visible_prompt_func = raw_input
16
17 _ansi_colors = ('black', 'red', 'green', 'yellow', 'blue', 'magenta',
18 'cyan', 'white', 'reset')
19 _ansi_reset_all = '\033[0m'
20
21
22 def hidden_prompt_func(prompt):
23 import getpass
24 return getpass.getpass(prompt)
25
26
27 def _build_prompt(text, suffix, show_default=False, default=None):
28 prompt = text
29 if default is not None and show_default:
30 prompt = '%s [%s]' % (prompt, default)
31 return prompt + suffix
32
33
34 def prompt(text, default=None, hide_input=False,
35 confirmation_prompt=False, type=None,
36 value_proc=None, prompt_suffix=': ',
37 show_default=True, err=False):
38 """Prompts a user for input. This is a convenience function that can
39 be used to prompt a user for input later.
40
41 If the user aborts the input by sending a interrupt signal, this
42 function will catch it and raise a :exc:`Abort` exception.
43
44 .. versionadded:: 4.0
45 Added the `err` parameter.
46
47 :param text: the text to show for the prompt.
48 :param default: the default value to use if no input happens. If this
49 is not given it will prompt until it's aborted.
50 :param hide_input: if this is set to true then the input value will
51 be hidden.
52 :param confirmation_prompt: asks for confirmation for the value.
53 :param type: the type to use to check the value against.
54 :param value_proc: if this parameter is provided it's a function that
55 is invoked instead of the type conversion to
56 convert a value.
57 :param prompt_suffix: a suffix that should be added to the prompt.
58 :param show_default: shows or hides the default value in the prompt.
59 :param err: if set to true the file defaults to ``stderr`` instead of
60 ``stdout``, the same as with echo.
61 """
62 result = None
63
64 def prompt_func(text):
65 f = hide_input and hidden_prompt_func or visible_prompt_func
66 try:
67 # Write the prompt separately so that we get nice
68 # coloring through colorama on Windows
69 echo(text, nl=False, err=err)
70 return f('')
71 except (KeyboardInterrupt, EOFError):
72 # getpass doesn't print a newline if the user aborts input with ^C.
73 # Allegedly this behavior is inherited from getpass(3).
74 # A doc bug has been filed at https://bugs.python.org/issue24711
75 if hide_input:
76 echo(None, err=err)
77 raise Abort()
78
79 if value_proc is None:
80 value_proc = convert_type(type, default)
81
82 prompt = _build_prompt(text, prompt_suffix, show_default, default)
83
84 while 1:
85 while 1:
86 value = prompt_func(prompt)
87 if value:
88 break
89 # If a default is set and used, then the confirmation
90 # prompt is always skipped because that's the only thing
91 # that really makes sense.
92 elif default is not None:
93 return default
94 try:
95 result = value_proc(value)
96 except UsageError as e:
97 echo('Error: %s' % e.message, err=err)
98 continue
99 if not confirmation_prompt:
100 return result
101 while 1:
102 value2 = prompt_func('Repeat for confirmation: ')
103 if value2:
104 break
105 if value == value2:
106 return result
107 echo('Error: the two entered values do not match', err=err)
108
109
110 def confirm(text, default=False, abort=False, prompt_suffix=': ',
111 show_default=True, err=False):
112 """Prompts for confirmation (yes/no question).
113
114 If the user aborts the input by sending a interrupt signal this
115 function will catch it and raise a :exc:`Abort` exception.
116
117 .. versionadded:: 4.0
118 Added the `err` parameter.
119
120 :param text: the question to ask.
121 :param default: the default for the prompt.
122 :param abort: if this is set to `True` a negative answer aborts the
123 exception by raising :exc:`Abort`.
124 :param prompt_suffix: a suffix that should be added to the prompt.
125 :param show_default: shows or hides the default value in the prompt.
126 :param err: if set to true the file defaults to ``stderr`` instead of
127 ``stdout``, the same as with echo.
128 """
129 prompt = _build_prompt(text, prompt_suffix, show_default,
130 default and 'Y/n' or 'y/N')
131 while 1:
132 try:
133 # Write the prompt separately so that we get nice
134 # coloring through colorama on Windows
135 echo(prompt, nl=False, err=err)
136 value = visible_prompt_func('').lower().strip()
137 except (KeyboardInterrupt, EOFError):
138 raise Abort()
139 if value in ('y', 'yes'):
140 rv = True
141 elif value in ('n', 'no'):
142 rv = False
143 elif value == '':
144 rv = default
145 else:
146 echo('Error: invalid input', err=err)
147 continue
148 break
149 if abort and not rv:
150 raise Abort()
151 return rv
152
153
154 def get_terminal_size():
155 """Returns the current size of the terminal as tuple in the form
156 ``(width, height)`` in columns and rows.
157 """
158 # If shutil has get_terminal_size() (Python 3.3 and later) use that
159 if sys.version_info >= (3, 3):
160 import shutil
161 shutil_get_terminal_size = getattr(shutil, 'get_terminal_size', None)
162 if shutil_get_terminal_size:
163 sz = shutil_get_terminal_size()
164 return sz.columns, sz.lines
165
166 if get_winterm_size is not None:
167 return get_winterm_size()
168
169 def ioctl_gwinsz(fd):
170 try:
171 import fcntl
172 import termios
173 cr = struct.unpack(
174 'hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
175 except Exception:
176 return
177 return cr
178
179 cr = ioctl_gwinsz(0) or ioctl_gwinsz(1) or ioctl_gwinsz(2)
180 if not cr:
181 try:
182 fd = os.open(os.ctermid(), os.O_RDONLY)
183 try:
184 cr = ioctl_gwinsz(fd)
185 finally:
186 os.close(fd)
187 except Exception:
188 pass
189 if not cr or not cr[0] or not cr[1]:
190 cr = (os.environ.get('LINES', 25),
191 os.environ.get('COLUMNS', DEFAULT_COLUMNS))
192 return int(cr[1]), int(cr[0])
193
194
195 def echo_via_pager(text, color=None):
196 """This function takes a text and shows it via an environment specific
197 pager on stdout.
198
199 .. versionchanged:: 3.0
200 Added the `color` flag.
201
202 :param text: the text to page.
203 :param color: controls if the pager supports ANSI colors or not. The
204 default is autodetection.
205 """
206 color = resolve_color_default(color)
207 if not isinstance(text, string_types):
208 text = text_type(text)
209 from ._termui_impl import pager
210 return pager(text + '\n', color)
211
212
213 def progressbar(iterable=None, length=None, label=None, show_eta=True,
214 show_percent=None, show_pos=False,
215 item_show_func=None, fill_char='#', empty_char='-',
216 bar_template='%(label)s [%(bar)s] %(info)s',
217 info_sep=' ', width=36, file=None, color=None):
218 """This function creates an iterable context manager that can be used
219 to iterate over something while showing a progress bar. It will
220 either iterate over the `iterable` or `length` items (that are counted
221 up). While iteration happens, this function will print a rendered
222 progress bar to the given `file` (defaults to stdout) and will attempt
223 to calculate remaining time and more. By default, this progress bar
224 will not be rendered if the file is not a terminal.
225
226 The context manager creates the progress bar. When the context
227 manager is entered the progress bar is already displayed. With every
228 iteration over the progress bar, the iterable passed to the bar is
229 advanced and the bar is updated. When the context manager exits,
230 a newline is printed and the progress bar is finalized on screen.
231
232 No printing must happen or the progress bar will be unintentionally
233 destroyed.
234
235 Example usage::
236
237 with progressbar(items) as bar:
238 for item in bar:
239 do_something_with(item)
240
241 Alternatively, if no iterable is specified, one can manually update the
242 progress bar through the `update()` method instead of directly
243 iterating over the progress bar. The update method accepts the number
244 of steps to increment the bar with::
245
246 with progressbar(length=chunks.total_bytes) as bar:
247 for chunk in chunks:
248 process_chunk(chunk)
249 bar.update(chunks.bytes)
250
251 .. versionadded:: 2.0
252
253 .. versionadded:: 4.0
254 Added the `color` parameter. Added a `update` method to the
255 progressbar object.
256
257 :param iterable: an iterable to iterate over. If not provided the length
258 is required.
259 :param length: the number of items to iterate over. By default the
260 progressbar will attempt to ask the iterator about its
261 length, which might or might not work. If an iterable is
262 also provided this parameter can be used to override the
263 length. If an iterable is not provided the progress bar
264 will iterate over a range of that length.
265 :param label: the label to show next to the progress bar.
266 :param show_eta: enables or disables the estimated time display. This is
267 automatically disabled if the length cannot be
268 determined.
269 :param show_percent: enables or disables the percentage display. The
270 default is `True` if the iterable has a length or
271 `False` if not.
272 :param show_pos: enables or disables the absolute position display. The
273 default is `False`.
274 :param item_show_func: a function called with the current item which
275 can return a string to show the current item
276 next to the progress bar. Note that the current
277 item can be `None`!
278 :param fill_char: the character to use to show the filled part of the
279 progress bar.
280 :param empty_char: the character to use to show the non-filled part of
281 the progress bar.
282 :param bar_template: the format string to use as template for the bar.
283 The parameters in it are ``label`` for the label,
284 ``bar`` for the progress bar and ``info`` for the
285 info section.
286 :param info_sep: the separator between multiple info items (eta etc.)
287 :param width: the width of the progress bar in characters, 0 means full
288 terminal width
289 :param file: the file to write to. If this is not a terminal then
290 only the label is printed.
291 :param color: controls if the terminal supports ANSI colors or not. The
292 default is autodetection. This is only needed if ANSI
293 codes are included anywhere in the progress bar output
294 which is not the case by default.
295 """
296 from ._termui_impl import ProgressBar
297 color = resolve_color_default(color)
298 return ProgressBar(iterable=iterable, length=length, show_eta=show_eta,
299 show_percent=show_percent, show_pos=show_pos,
300 item_show_func=item_show_func, fill_char=fill_char,
301 empty_char=empty_char, bar_template=bar_template,
302 info_sep=info_sep, file=file, label=label,
303 width=width, color=color)
304
305
306 def clear():
307 """Clears the terminal screen. This will have the effect of clearing
308 the whole visible space of the terminal and moving the cursor to the
309 top left. This does not do anything if not connected to a terminal.
310
311 .. versionadded:: 2.0
312 """
313 if not isatty(sys.stdout):
314 return
315 # If we're on Windows and we don't have colorama available, then we
316 # clear the screen by shelling out. Otherwise we can use an escape
317 # sequence.
318 if WIN:
319 os.system('cls')
320 else:
321 sys.stdout.write('\033[2J\033[1;1H')
322
323
324 def style(text, fg=None, bg=None, bold=None, dim=None, underline=None,
325 blink=None, reverse=None, reset=True):
326 """Styles a text with ANSI styles and returns the new string. By
327 default the styling is self contained which means that at the end
328 of the string a reset code is issued. This can be prevented by
329 passing ``reset=False``.
330
331 Examples::
332
333 click.echo(click.style('Hello World!', fg='green'))
334 click.echo(click.style('ATTENTION!', blink=True))
335 click.echo(click.style('Some things', reverse=True, fg='cyan'))
336
337 Supported color names:
338
339 * ``black`` (might be a gray)
340 * ``red``
341 * ``green``
342 * ``yellow`` (might be an orange)
343 * ``blue``
344 * ``magenta``
345 * ``cyan``
346 * ``white`` (might be light gray)
347 * ``reset`` (reset the color code only)
348
349 .. versionadded:: 2.0
350
351 :param text: the string to style with ansi codes.
352 :param fg: if provided this will become the foreground color.
353 :param bg: if provided this will become the background color.
354 :param bold: if provided this will enable or disable bold mode.
355 :param dim: if provided this will enable or disable dim mode. This is
356 badly supported.
357 :param underline: if provided this will enable or disable underline.
358 :param blink: if provided this will enable or disable blinking.
359 :param reverse: if provided this will enable or disable inverse
360 rendering (foreground becomes background and the
361 other way round).
362 :param reset: by default a reset-all code is added at the end of the
363 string which means that styles do not carry over. This
364 can be disabled to compose styles.
365 """
366 bits = []
367 if fg:
368 try:
369 bits.append('\033[%dm' % (_ansi_colors.index(fg) + 30))
370 except ValueError:
371 raise TypeError('Unknown color %r' % fg)
372 if bg:
373 try:
374 bits.append('\033[%dm' % (_ansi_colors.index(bg) + 40))
375 except ValueError:
376 raise TypeError('Unknown color %r' % bg)
377 if bold is not None:
378 bits.append('\033[%dm' % (1 if bold else 22))
379 if dim is not None:
380 bits.append('\033[%dm' % (2 if dim else 22))
381 if underline is not None:
382 bits.append('\033[%dm' % (4 if underline else 24))
383 if blink is not None:
384 bits.append('\033[%dm' % (5 if blink else 25))
385 if reverse is not None:
386 bits.append('\033[%dm' % (7 if reverse else 27))
387 bits.append(text)
388 if reset:
389 bits.append(_ansi_reset_all)
390 return ''.join(bits)
391
392
393 def unstyle(text):
394 """Removes ANSI styling information from a string. Usually it's not
395 necessary to use this function as Click's echo function will
396 automatically remove styling if necessary.
397
398 .. versionadded:: 2.0
399
400 :param text: the text to remove style information from.
401 """
402 return strip_ansi(text)
403
404
405 def secho(text, file=None, nl=True, err=False, color=None, **styles):
406 """This function combines :func:`echo` and :func:`style` into one
407 call. As such the following two calls are the same::
408
409 click.secho('Hello World!', fg='green')
410 click.echo(click.style('Hello World!', fg='green'))
411
412 All keyword arguments are forwarded to the underlying functions
413 depending on which one they go with.
414
415 .. versionadded:: 2.0
416 """
417 return echo(style(text, **styles), file=file, nl=nl, err=err, color=color)
418
419
420 def edit(text=None, editor=None, env=None, require_save=True,
421 extension='.txt', filename=None):
422 r"""Edits the given text in the defined editor. If an editor is given
423 (should be the full path to the executable but the regular operating
424 system search path is used for finding the executable) it overrides
425 the detected editor. Optionally, some environment variables can be
426 used. If the editor is closed without changes, `None` is returned. In
427 case a file is edited directly the return value is always `None` and
428 `require_save` and `extension` are ignored.
429
430 If the editor cannot be opened a :exc:`UsageError` is raised.
431
432 Note for Windows: to simplify cross-platform usage, the newlines are
433 automatically converted from POSIX to Windows and vice versa. As such,
434 the message here will have ``\n`` as newline markers.
435
436 :param text: the text to edit.
437 :param editor: optionally the editor to use. Defaults to automatic
438 detection.
439 :param env: environment variables to forward to the editor.
440 :param require_save: if this is true, then not saving in the editor
441 will make the return value become `None`.
442 :param extension: the extension to tell the editor about. This defaults
443 to `.txt` but changing this might change syntax
444 highlighting.
445 :param filename: if provided it will edit this file instead of the
446 provided text contents. It will not use a temporary
447 file as an indirection in that case.
448 """
449 from ._termui_impl import Editor
450 editor = Editor(editor=editor, env=env, require_save=require_save,
451 extension=extension)
452 if filename is None:
453 return editor.edit(text)
454 editor.edit_file(filename)
455
456
457 def launch(url, wait=False, locate=False):
458 """This function launches the given URL (or filename) in the default
459 viewer application for this file type. If this is an executable, it
460 might launch the executable in a new session. The return value is
461 the exit code of the launched application. Usually, ``0`` indicates
462 success.
463
464 Examples::
465
466 click.launch('http://click.pocoo.org/')
467 click.launch('/my/downloaded/file', locate=True)
468
469 .. versionadded:: 2.0
470
471 :param url: URL or filename of the thing to launch.
472 :param wait: waits for the program to stop.
473 :param locate: if this is set to `True` then instead of launching the
474 application associated with the URL it will attempt to
475 launch a file manager with the file located. This
476 might have weird effects if the URL does not point to
477 the filesystem.
478 """
479 from ._termui_impl import open_url
480 return open_url(url, wait=wait, locate=locate)
481
482
483 # If this is provided, getchar() calls into this instead. This is used
484 # for unittesting purposes.
485 _getchar = None
486
487
488 def getchar(echo=False):
489 """Fetches a single character from the terminal and returns it. This
490 will always return a unicode character and under certain rare
491 circumstances this might return more than one character. The
492 situations which more than one character is returned is when for
493 whatever reason multiple characters end up in the terminal buffer or
494 standard input was not actually a terminal.
495
496 Note that this will always read from the terminal, even if something
497 is piped into the standard input.
498
499 .. versionadded:: 2.0
500
501 :param echo: if set to `True`, the character read will also show up on
502 the terminal. The default is to not show it.
503 """
504 f = _getchar
505 if f is None:
506 from ._termui_impl import getchar as f
507 return f(echo)
508
509
510 def pause(info='Press any key to continue ...', err=False):
511 """This command stops execution and waits for the user to press any
512 key to continue. This is similar to the Windows batch "pause"
513 command. If the program is not run through a terminal, this command
514 will instead do nothing.
515
516 .. versionadded:: 2.0
517
518 .. versionadded:: 4.0
519 Added the `err` parameter.
520
521 :param info: the info string to print before pausing.
522 :param err: if set to message goes to ``stderr`` instead of
523 ``stdout``, the same as with echo.
524 """
525 if not isatty(sys.stdin) or not isatty(sys.stdout):
526 return
527 try:
528 if info:
529 echo(info, nl=False, err=err)
530 try:
531 getchar()
532 except (KeyboardInterrupt, EOFError):
533 pass
534 finally:
535 if info:
536 echo(err=err)