termui.py 21 KB

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