termui.py 23 KB

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