图片解析应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

776 lines
30 KiB

  1. # Human friendly input/output in Python.
  2. #
  3. # Author: Peter Odding <peter@peterodding.com>
  4. # Last Change: March 1, 2020
  5. # URL: https://humanfriendly.readthedocs.io
  6. """
  7. Interaction with interactive text terminals.
  8. The :mod:`~humanfriendly.terminal` module makes it easy to interact with
  9. interactive text terminals and format text for rendering on such terminals. If
  10. the terms used in the documentation of this module don't make sense to you then
  11. please refer to the `Wikipedia article on ANSI escape sequences`_ for details
  12. about how ANSI escape sequences work.
  13. This module was originally developed for use on UNIX systems, but since then
  14. Windows 10 gained native support for ANSI escape sequences and this module was
  15. enhanced to recognize and support this. For details please refer to the
  16. :func:`enable_ansi_support()` function.
  17. .. _Wikipedia article on ANSI escape sequences: http://en.wikipedia.org/wiki/ANSI_escape_code#Sequence_elements
  18. """
  19. # Standard library modules.
  20. import codecs
  21. import numbers
  22. import os
  23. import platform
  24. import re
  25. import subprocess
  26. import sys
  27. # The `fcntl' module is platform specific so importing it may give an error. We
  28. # hide this implementation detail from callers by handling the import error and
  29. # setting a flag instead.
  30. try:
  31. import fcntl
  32. import termios
  33. import struct
  34. HAVE_IOCTL = True
  35. except ImportError:
  36. HAVE_IOCTL = False
  37. # Modules included in our package.
  38. from humanfriendly.compat import coerce_string, is_unicode, on_windows, which
  39. from humanfriendly.decorators import cached
  40. from humanfriendly.deprecation import define_aliases
  41. from humanfriendly.text import concatenate, format
  42. from humanfriendly.usage import format_usage
  43. # Public identifiers that require documentation.
  44. __all__ = (
  45. 'ANSI_COLOR_CODES',
  46. 'ANSI_CSI',
  47. 'ANSI_ERASE_LINE',
  48. 'ANSI_HIDE_CURSOR',
  49. 'ANSI_RESET',
  50. 'ANSI_SGR',
  51. 'ANSI_SHOW_CURSOR',
  52. 'ANSI_TEXT_STYLES',
  53. 'CLEAN_OUTPUT_PATTERN',
  54. 'DEFAULT_COLUMNS',
  55. 'DEFAULT_ENCODING',
  56. 'DEFAULT_LINES',
  57. 'HIGHLIGHT_COLOR',
  58. 'ansi_strip',
  59. 'ansi_style',
  60. 'ansi_width',
  61. 'ansi_wrap',
  62. 'auto_encode',
  63. 'clean_terminal_output',
  64. 'connected_to_terminal',
  65. 'enable_ansi_support',
  66. 'find_terminal_size',
  67. 'find_terminal_size_using_ioctl',
  68. 'find_terminal_size_using_stty',
  69. 'get_pager_command',
  70. 'have_windows_native_ansi_support',
  71. 'message',
  72. 'output',
  73. 'readline_strip',
  74. 'readline_wrap',
  75. 'show_pager',
  76. 'terminal_supports_colors',
  77. 'usage',
  78. 'warning',
  79. )
  80. ANSI_CSI = '\x1b['
  81. """The ANSI "Control Sequence Introducer" (a string)."""
  82. ANSI_SGR = 'm'
  83. """The ANSI "Select Graphic Rendition" sequence (a string)."""
  84. ANSI_ERASE_LINE = '%sK' % ANSI_CSI
  85. """The ANSI escape sequence to erase the current line (a string)."""
  86. ANSI_RESET = '%s0%s' % (ANSI_CSI, ANSI_SGR)
  87. """The ANSI escape sequence to reset styling (a string)."""
  88. ANSI_HIDE_CURSOR = '%s?25l' % ANSI_CSI
  89. """The ANSI escape sequence to hide the text cursor (a string)."""
  90. ANSI_SHOW_CURSOR = '%s?25h' % ANSI_CSI
  91. """The ANSI escape sequence to show the text cursor (a string)."""
  92. ANSI_COLOR_CODES = dict(black=0, red=1, green=2, yellow=3, blue=4, magenta=5, cyan=6, white=7)
  93. """
  94. A dictionary with (name, number) pairs of `portable color codes`_. Used by
  95. :func:`ansi_style()` to generate ANSI escape sequences that change font color.
  96. .. _portable color codes: http://en.wikipedia.org/wiki/ANSI_escape_code#Colors
  97. """
  98. ANSI_TEXT_STYLES = dict(bold=1, faint=2, italic=3, underline=4, inverse=7, strike_through=9)
  99. """
  100. A dictionary with (name, number) pairs of text styles (effects). Used by
  101. :func:`ansi_style()` to generate ANSI escape sequences that change text
  102. styles. Only widely supported text styles are included here.
  103. """
  104. CLEAN_OUTPUT_PATTERN = re.compile(u'(\r|\n|\b|%s)' % re.escape(ANSI_ERASE_LINE))
  105. """
  106. A compiled regular expression used to separate significant characters from other text.
  107. This pattern is used by :func:`clean_terminal_output()` to split terminal
  108. output into regular text versus backspace, carriage return and line feed
  109. characters and ANSI 'erase line' escape sequences.
  110. """
  111. DEFAULT_LINES = 25
  112. """The default number of lines in a terminal (an integer)."""
  113. DEFAULT_COLUMNS = 80
  114. """The default number of columns in a terminal (an integer)."""
  115. DEFAULT_ENCODING = 'UTF-8'
  116. """The output encoding for Unicode strings."""
  117. HIGHLIGHT_COLOR = os.environ.get('HUMANFRIENDLY_HIGHLIGHT_COLOR', 'green')
  118. """
  119. The color used to highlight important tokens in formatted text (e.g. the usage
  120. message of the ``humanfriendly`` program). If the environment variable
  121. ``$HUMANFRIENDLY_HIGHLIGHT_COLOR`` is set it determines the value of
  122. :data:`HIGHLIGHT_COLOR`.
  123. """
  124. def ansi_strip(text, readline_hints=True):
  125. """
  126. Strip ANSI escape sequences from the given string.
  127. :param text: The text from which ANSI escape sequences should be removed (a
  128. string).
  129. :param readline_hints: If :data:`True` then :func:`readline_strip()` is
  130. used to remove `readline hints`_ from the string.
  131. :returns: The text without ANSI escape sequences (a string).
  132. """
  133. pattern = '%s.*?%s' % (re.escape(ANSI_CSI), re.escape(ANSI_SGR))
  134. text = re.sub(pattern, '', text)
  135. if readline_hints:
  136. text = readline_strip(text)
  137. return text
  138. def ansi_style(**kw):
  139. """
  140. Generate ANSI escape sequences for the given color and/or style(s).
  141. :param color: The foreground color. Three types of values are supported:
  142. - The name of a color (one of the strings 'black', 'red',
  143. 'green', 'yellow', 'blue', 'magenta', 'cyan' or 'white').
  144. - An integer that refers to the 256 color mode palette.
  145. - A tuple or list with three integers representing an RGB
  146. (red, green, blue) value.
  147. The value :data:`None` (the default) means no escape
  148. sequence to switch color will be emitted.
  149. :param background: The background color (see the description
  150. of the `color` argument).
  151. :param bright: Use high intensity colors instead of default colors
  152. (a boolean, defaults to :data:`False`).
  153. :param readline_hints: If :data:`True` then :func:`readline_wrap()` is
  154. applied to the generated ANSI escape sequences (the
  155. default is :data:`False`).
  156. :param kw: Any additional keyword arguments are expected to match a key
  157. in the :data:`ANSI_TEXT_STYLES` dictionary. If the argument's
  158. value evaluates to :data:`True` the respective style will be
  159. enabled.
  160. :returns: The ANSI escape sequences to enable the requested text styles or
  161. an empty string if no styles were requested.
  162. :raises: :exc:`~exceptions.ValueError` when an invalid color name is given.
  163. Even though only eight named colors are supported, the use of `bright=True`
  164. and `faint=True` increases the number of available colors to around 24 (it
  165. may be slightly lower, for example because faint black is just black).
  166. **Support for 8-bit colors**
  167. In `release 4.7`_ support for 256 color mode was added. While this
  168. significantly increases the available colors it's not very human friendly
  169. in usage because you need to look up color codes in the `256 color mode
  170. palette <https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit>`_.
  171. You can use the ``humanfriendly --demo`` command to get a demonstration of
  172. the available colors, see also the screen shot below. Note that the small
  173. font size in the screen shot was so that the demonstration of 256 color
  174. mode support would fit into a single screen shot without scrolling :-)
  175. (I wasn't feeling very creative).
  176. .. image:: images/ansi-demo.png
  177. **Support for 24-bit colors**
  178. In `release 4.14`_ support for 24-bit colors was added by accepting a tuple
  179. or list with three integers representing the RGB (red, green, blue) value
  180. of a color. This is not included in the demo because rendering millions of
  181. colors was deemed unpractical ;-).
  182. .. _release 4.7: http://humanfriendly.readthedocs.io/en/latest/changelog.html#release-4-7-2018-01-14
  183. .. _release 4.14: http://humanfriendly.readthedocs.io/en/latest/changelog.html#release-4-14-2018-07-13
  184. """
  185. # Start with sequences that change text styles.
  186. sequences = [ANSI_TEXT_STYLES[k] for k, v in kw.items() if k in ANSI_TEXT_STYLES and v]
  187. # Append the color code (if any).
  188. for color_type in 'color', 'background':
  189. color_value = kw.get(color_type)
  190. if isinstance(color_value, (tuple, list)):
  191. if len(color_value) != 3:
  192. msg = "Invalid color value %r! (expected tuple or list with three numbers)"
  193. raise ValueError(msg % color_value)
  194. sequences.append(48 if color_type == 'background' else 38)
  195. sequences.append(2)
  196. sequences.extend(map(int, color_value))
  197. elif isinstance(color_value, numbers.Number):
  198. # Numeric values are assumed to be 256 color codes.
  199. sequences.extend((
  200. 39 if color_type == 'background' else 38,
  201. 5, int(color_value)
  202. ))
  203. elif color_value:
  204. # Other values are assumed to be strings containing one of the known color names.
  205. if color_value not in ANSI_COLOR_CODES:
  206. msg = "Invalid color value %r! (expected an integer or one of the strings %s)"
  207. raise ValueError(msg % (color_value, concatenate(map(repr, sorted(ANSI_COLOR_CODES)))))
  208. # Pick the right offset for foreground versus background
  209. # colors and regular intensity versus bright colors.
  210. offset = (
  211. (100 if kw.get('bright') else 40)
  212. if color_type == 'background'
  213. else (90 if kw.get('bright') else 30)
  214. )
  215. # Combine the offset and color code into a single integer.
  216. sequences.append(offset + ANSI_COLOR_CODES[color_value])
  217. if sequences:
  218. encoded = ANSI_CSI + ';'.join(map(str, sequences)) + ANSI_SGR
  219. return readline_wrap(encoded) if kw.get('readline_hints') else encoded
  220. else:
  221. return ''
  222. def ansi_width(text):
  223. """
  224. Calculate the effective width of the given text (ignoring ANSI escape sequences).
  225. :param text: The text whose width should be calculated (a string).
  226. :returns: The width of the text without ANSI escape sequences (an
  227. integer).
  228. This function uses :func:`ansi_strip()` to strip ANSI escape sequences from
  229. the given string and returns the length of the resulting string.
  230. """
  231. return len(ansi_strip(text))
  232. def ansi_wrap(text, **kw):
  233. """
  234. Wrap text in ANSI escape sequences for the given color and/or style(s).
  235. :param text: The text to wrap (a string).
  236. :param kw: Any keyword arguments are passed to :func:`ansi_style()`.
  237. :returns: The result of this function depends on the keyword arguments:
  238. - If :func:`ansi_style()` generates an ANSI escape sequence based
  239. on the keyword arguments, the given text is prefixed with the
  240. generated ANSI escape sequence and suffixed with
  241. :data:`ANSI_RESET`.
  242. - If :func:`ansi_style()` returns an empty string then the text
  243. given by the caller is returned unchanged.
  244. """
  245. start_sequence = ansi_style(**kw)
  246. if start_sequence:
  247. end_sequence = ANSI_RESET
  248. if kw.get('readline_hints'):
  249. end_sequence = readline_wrap(end_sequence)
  250. return start_sequence + text + end_sequence
  251. else:
  252. return text
  253. def auto_encode(stream, text, *args, **kw):
  254. """
  255. Reliably write Unicode strings to the terminal.
  256. :param stream: The file-like object to write to (a value like
  257. :data:`sys.stdout` or :data:`sys.stderr`).
  258. :param text: The text to write to the stream (a string).
  259. :param args: Refer to :func:`~humanfriendly.text.format()`.
  260. :param kw: Refer to :func:`~humanfriendly.text.format()`.
  261. Renders the text using :func:`~humanfriendly.text.format()` and writes it
  262. to the given stream. If an :exc:`~exceptions.UnicodeEncodeError` is
  263. encountered in doing so, the text is encoded using :data:`DEFAULT_ENCODING`
  264. and the write is retried. The reasoning behind this rather blunt approach
  265. is that it's preferable to get output on the command line in the wrong
  266. encoding then to have the Python program blow up with a
  267. :exc:`~exceptions.UnicodeEncodeError` exception.
  268. """
  269. text = format(text, *args, **kw)
  270. try:
  271. stream.write(text)
  272. except UnicodeEncodeError:
  273. stream.write(codecs.encode(text, DEFAULT_ENCODING))
  274. def clean_terminal_output(text):
  275. """
  276. Clean up the terminal output of a command.
  277. :param text: The raw text with special characters (a Unicode string).
  278. :returns: A list of Unicode strings (one for each line).
  279. This function emulates the effect of backspace (0x08), carriage return
  280. (0x0D) and line feed (0x0A) characters and the ANSI 'erase line' escape
  281. sequence on interactive terminals. It's intended to clean up command output
  282. that was originally meant to be rendered on an interactive terminal and
  283. that has been captured using e.g. the :man:`script` program [#]_ or the
  284. :mod:`pty` module [#]_.
  285. .. [#] My coloredlogs_ package supports the ``coloredlogs --to-html``
  286. command which uses :man:`script` to fool a subprocess into thinking
  287. that it's connected to an interactive terminal (in order to get it
  288. to emit ANSI escape sequences).
  289. .. [#] My capturer_ package uses the :mod:`pty` module to fool the current
  290. process and subprocesses into thinking they are connected to an
  291. interactive terminal (in order to get them to emit ANSI escape
  292. sequences).
  293. **Some caveats about the use of this function:**
  294. - Strictly speaking the effect of carriage returns cannot be emulated
  295. outside of an actual terminal due to the interaction between overlapping
  296. output, terminal widths and line wrapping. The goal of this function is
  297. to sanitize noise in terminal output while preserving useful output.
  298. Think of it as a useful and pragmatic but possibly lossy conversion.
  299. - The algorithm isn't smart enough to properly handle a pair of ANSI escape
  300. sequences that open before a carriage return and close after the last
  301. carriage return in a linefeed delimited string; the resulting string will
  302. contain only the closing end of the ANSI escape sequence pair. Tracking
  303. this kind of complexity requires a state machine and proper parsing.
  304. .. _capturer: https://pypi.org/project/capturer
  305. .. _coloredlogs: https://pypi.org/project/coloredlogs
  306. """
  307. cleaned_lines = []
  308. current_line = ''
  309. current_position = 0
  310. for token in CLEAN_OUTPUT_PATTERN.split(text):
  311. if token == '\r':
  312. # Seek back to the start of the current line.
  313. current_position = 0
  314. elif token == '\b':
  315. # Seek back one character in the current line.
  316. current_position = max(0, current_position - 1)
  317. else:
  318. if token == '\n':
  319. # Capture the current line.
  320. cleaned_lines.append(current_line)
  321. if token in ('\n', ANSI_ERASE_LINE):
  322. # Clear the current line.
  323. current_line = ''
  324. current_position = 0
  325. elif token:
  326. # Merge regular output into the current line.
  327. new_position = current_position + len(token)
  328. prefix = current_line[:current_position]
  329. suffix = current_line[new_position:]
  330. current_line = prefix + token + suffix
  331. current_position = new_position
  332. # Capture the last line (if any).
  333. cleaned_lines.append(current_line)
  334. # Remove any empty trailing lines.
  335. while cleaned_lines and not cleaned_lines[-1]:
  336. cleaned_lines.pop(-1)
  337. return cleaned_lines
  338. def connected_to_terminal(stream=None):
  339. """
  340. Check if a stream is connected to a terminal.
  341. :param stream: The stream to check (a file-like object,
  342. defaults to :data:`sys.stdout`).
  343. :returns: :data:`True` if the stream is connected to a terminal,
  344. :data:`False` otherwise.
  345. See also :func:`terminal_supports_colors()`.
  346. """
  347. stream = sys.stdout if stream is None else stream
  348. try:
  349. return stream.isatty()
  350. except Exception:
  351. return False
  352. @cached
  353. def enable_ansi_support():
  354. """
  355. Try to enable support for ANSI escape sequences (required on Windows).
  356. :returns: :data:`True` if ANSI is supported, :data:`False` otherwise.
  357. This functions checks for the following supported configurations, in the
  358. given order:
  359. 1. On Windows, if :func:`have_windows_native_ansi_support()` confirms
  360. native support for ANSI escape sequences :mod:`ctypes` will be used to
  361. enable this support.
  362. 2. On Windows, if the environment variable ``$ANSICON`` is set nothing is
  363. done because it is assumed that support for ANSI escape sequences has
  364. already been enabled via `ansicon <https://github.com/adoxa/ansicon>`_.
  365. 3. On Windows, an attempt is made to import and initialize the Python
  366. package :pypi:`colorama` instead (of course for this to work
  367. :pypi:`colorama` has to be installed).
  368. 4. On other platforms this function calls :func:`connected_to_terminal()`
  369. to determine whether ANSI escape sequences are supported (that is to
  370. say all platforms that are not Windows are assumed to support ANSI
  371. escape sequences natively, without weird contortions like above).
  372. This makes it possible to call :func:`enable_ansi_support()`
  373. unconditionally without checking the current platform.
  374. The :func:`~humanfriendly.decorators.cached` decorator is used to ensure
  375. that this function is only executed once, but its return value remains
  376. available on later calls.
  377. """
  378. if have_windows_native_ansi_support():
  379. import ctypes
  380. ctypes.windll.kernel32.SetConsoleMode(ctypes.windll.kernel32.GetStdHandle(-11), 7)
  381. ctypes.windll.kernel32.SetConsoleMode(ctypes.windll.kernel32.GetStdHandle(-12), 7)
  382. return True
  383. elif on_windows():
  384. if 'ANSICON' in os.environ:
  385. return True
  386. try:
  387. import colorama
  388. colorama.init()
  389. return True
  390. except ImportError:
  391. return False
  392. else:
  393. return connected_to_terminal()
  394. def find_terminal_size():
  395. """
  396. Determine the number of lines and columns visible in the terminal.
  397. :returns: A tuple of two integers with the line and column count.
  398. The result of this function is based on the first of the following three
  399. methods that works:
  400. 1. First :func:`find_terminal_size_using_ioctl()` is tried,
  401. 2. then :func:`find_terminal_size_using_stty()` is tried,
  402. 3. finally :data:`DEFAULT_LINES` and :data:`DEFAULT_COLUMNS` are returned.
  403. .. note:: The :func:`find_terminal_size()` function performs the steps
  404. above every time it is called, the result is not cached. This is
  405. because the size of a virtual terminal can change at any time and
  406. the result of :func:`find_terminal_size()` should be correct.
  407. `Pre-emptive snarky comment`_: It's possible to cache the result
  408. of this function and use :mod:`signal.SIGWINCH <signal>` to
  409. refresh the cached values!
  410. Response: As a library I don't consider it the role of the
  411. :mod:`humanfriendly.terminal` module to install a process wide
  412. signal handler ...
  413. .. _Pre-emptive snarky comment: http://blogs.msdn.com/b/oldnewthing/archive/2008/01/30/7315957.aspx
  414. """
  415. # The first method. Any of the standard streams may have been redirected
  416. # somewhere and there's no telling which, so we'll just try them all.
  417. for stream in sys.stdin, sys.stdout, sys.stderr:
  418. try:
  419. result = find_terminal_size_using_ioctl(stream)
  420. if min(result) >= 1:
  421. return result
  422. except Exception:
  423. pass
  424. # The second method.
  425. try:
  426. result = find_terminal_size_using_stty()
  427. if min(result) >= 1:
  428. return result
  429. except Exception:
  430. pass
  431. # Fall back to conservative defaults.
  432. return DEFAULT_LINES, DEFAULT_COLUMNS
  433. def find_terminal_size_using_ioctl(stream):
  434. """
  435. Find the terminal size using :func:`fcntl.ioctl()`.
  436. :param stream: A stream connected to the terminal (a file object with a
  437. ``fileno`` attribute).
  438. :returns: A tuple of two integers with the line and column count.
  439. :raises: This function can raise exceptions but I'm not going to document
  440. them here, you should be using :func:`find_terminal_size()`.
  441. Based on an `implementation found on StackOverflow <http://stackoverflow.com/a/3010495/788200>`_.
  442. """
  443. if not HAVE_IOCTL:
  444. raise NotImplementedError("It looks like the `fcntl' module is not available!")
  445. h, w, hp, wp = struct.unpack('HHHH', fcntl.ioctl(stream, termios.TIOCGWINSZ, struct.pack('HHHH', 0, 0, 0, 0)))
  446. return h, w
  447. def find_terminal_size_using_stty():
  448. """
  449. Find the terminal size using the external command ``stty size``.
  450. :param stream: A stream connected to the terminal (a file object).
  451. :returns: A tuple of two integers with the line and column count.
  452. :raises: This function can raise exceptions but I'm not going to document
  453. them here, you should be using :func:`find_terminal_size()`.
  454. """
  455. stty = subprocess.Popen(['stty', 'size'],
  456. stdout=subprocess.PIPE,
  457. stderr=subprocess.PIPE)
  458. stdout, stderr = stty.communicate()
  459. tokens = stdout.split()
  460. if len(tokens) != 2:
  461. raise Exception("Invalid output from `stty size'!")
  462. return tuple(map(int, tokens))
  463. def get_pager_command(text=None):
  464. """
  465. Get the command to show a text on the terminal using a pager.
  466. :param text: The text to print to the terminal (a string).
  467. :returns: A list of strings with the pager command and arguments.
  468. The use of a pager helps to avoid the wall of text effect where the user
  469. has to scroll up to see where the output began (not very user friendly).
  470. If the given text contains ANSI escape sequences the command ``less
  471. --RAW-CONTROL-CHARS`` is used, otherwise the environment variable
  472. ``$PAGER`` is used (if ``$PAGER`` isn't set :man:`less` is used).
  473. When the selected pager is :man:`less`, the following options are used to
  474. make the experience more user friendly:
  475. - ``--quit-if-one-screen`` causes :man:`less` to automatically exit if the
  476. entire text can be displayed on the first screen. This makes the use of a
  477. pager transparent for smaller texts (because the operator doesn't have to
  478. quit the pager).
  479. - ``--no-init`` prevents :man:`less` from clearing the screen when it
  480. exits. This ensures that the operator gets a chance to review the text
  481. (for example a usage message) after quitting the pager, while composing
  482. the next command.
  483. """
  484. # Compose the pager command.
  485. if text and ANSI_CSI in text:
  486. command_line = ['less', '--RAW-CONTROL-CHARS']
  487. else:
  488. command_line = [os.environ.get('PAGER', 'less')]
  489. # Pass some additional options to `less' (to make it more
  490. # user friendly) without breaking support for other pagers.
  491. if os.path.basename(command_line[0]) == 'less':
  492. command_line.append('--no-init')
  493. command_line.append('--quit-if-one-screen')
  494. return command_line
  495. @cached
  496. def have_windows_native_ansi_support():
  497. """
  498. Check if we're running on a Windows 10 release with native support for ANSI escape sequences.
  499. :returns: :data:`True` if so, :data:`False` otherwise.
  500. The :func:`~humanfriendly.decorators.cached` decorator is used as a minor
  501. performance optimization. Semantically this should have zero impact because
  502. the answer doesn't change in the lifetime of a computer process.
  503. """
  504. if on_windows():
  505. try:
  506. # I can't be 100% sure this will never break and I'm not in a
  507. # position to test it thoroughly either, so I decided that paying
  508. # the price of one additional try / except statement is worth the
  509. # additional peace of mind :-).
  510. components = tuple(int(c) for c in platform.version().split('.'))
  511. return components >= (10, 0, 14393)
  512. except Exception:
  513. pass
  514. return False
  515. def message(text, *args, **kw):
  516. """
  517. Print a formatted message to the standard error stream.
  518. For details about argument handling please refer to
  519. :func:`~humanfriendly.text.format()`.
  520. Renders the message using :func:`~humanfriendly.text.format()` and writes
  521. the resulting string (followed by a newline) to :data:`sys.stderr` using
  522. :func:`auto_encode()`.
  523. """
  524. auto_encode(sys.stderr, coerce_string(text) + '\n', *args, **kw)
  525. def output(text, *args, **kw):
  526. """
  527. Print a formatted message to the standard output stream.
  528. For details about argument handling please refer to
  529. :func:`~humanfriendly.text.format()`.
  530. Renders the message using :func:`~humanfriendly.text.format()` and writes
  531. the resulting string (followed by a newline) to :data:`sys.stdout` using
  532. :func:`auto_encode()`.
  533. """
  534. auto_encode(sys.stdout, coerce_string(text) + '\n', *args, **kw)
  535. def readline_strip(expr):
  536. """
  537. Remove `readline hints`_ from a string.
  538. :param text: The text to strip (a string).
  539. :returns: The stripped text.
  540. """
  541. return expr.replace('\001', '').replace('\002', '')
  542. def readline_wrap(expr):
  543. """
  544. Wrap an ANSI escape sequence in `readline hints`_.
  545. :param text: The text with the escape sequence to wrap (a string).
  546. :returns: The wrapped text.
  547. .. _readline hints: http://superuser.com/a/301355
  548. """
  549. return '\001' + expr + '\002'
  550. def show_pager(formatted_text, encoding=DEFAULT_ENCODING):
  551. """
  552. Print a large text to the terminal using a pager.
  553. :param formatted_text: The text to print to the terminal (a string).
  554. :param encoding: The name of the text encoding used to encode the formatted
  555. text if the formatted text is a Unicode string (a string,
  556. defaults to :data:`DEFAULT_ENCODING`).
  557. When :func:`connected_to_terminal()` returns :data:`True` a pager is used
  558. to show the text on the terminal, otherwise the text is printed directly
  559. without invoking a pager.
  560. The use of a pager helps to avoid the wall of text effect where the user
  561. has to scroll up to see where the output began (not very user friendly).
  562. Refer to :func:`get_pager_command()` for details about the command line
  563. that's used to invoke the pager.
  564. """
  565. if connected_to_terminal():
  566. # Make sure the selected pager command is available.
  567. command_line = get_pager_command(formatted_text)
  568. if which(command_line[0]):
  569. pager = subprocess.Popen(command_line, stdin=subprocess.PIPE)
  570. if is_unicode(formatted_text):
  571. formatted_text = formatted_text.encode(encoding)
  572. pager.communicate(input=formatted_text)
  573. return
  574. output(formatted_text)
  575. def terminal_supports_colors(stream=None):
  576. """
  577. Check if a stream is connected to a terminal that supports ANSI escape sequences.
  578. :param stream: The stream to check (a file-like object,
  579. defaults to :data:`sys.stdout`).
  580. :returns: :data:`True` if the terminal supports ANSI escape sequences,
  581. :data:`False` otherwise.
  582. This function was originally inspired by the implementation of
  583. `django.core.management.color.supports_color()
  584. <https://github.com/django/django/blob/master/django/core/management/color.py>`_
  585. but has since evolved significantly.
  586. """
  587. if on_windows():
  588. # On Windows support for ANSI escape sequences is not a given.
  589. have_ansicon = 'ANSICON' in os.environ
  590. have_colorama = 'colorama' in sys.modules
  591. have_native_support = have_windows_native_ansi_support()
  592. if not (have_ansicon or have_colorama or have_native_support):
  593. return False
  594. return connected_to_terminal(stream)
  595. def usage(usage_text):
  596. """
  597. Print a human friendly usage message to the terminal.
  598. :param text: The usage message to print (a string).
  599. This function does two things:
  600. 1. If :data:`sys.stdout` is connected to a terminal (see
  601. :func:`connected_to_terminal()`) then the usage message is formatted
  602. using :func:`.format_usage()`.
  603. 2. The usage message is shown using a pager (see :func:`show_pager()`).
  604. """
  605. if terminal_supports_colors(sys.stdout):
  606. usage_text = format_usage(usage_text)
  607. show_pager(usage_text)
  608. def warning(text, *args, **kw):
  609. """
  610. Show a warning message on the terminal.
  611. For details about argument handling please refer to
  612. :func:`~humanfriendly.text.format()`.
  613. Renders the message using :func:`~humanfriendly.text.format()` and writes
  614. the resulting string (followed by a newline) to :data:`sys.stderr` using
  615. :func:`auto_encode()`.
  616. If :data:`sys.stderr` is connected to a terminal that supports colors,
  617. :func:`ansi_wrap()` is used to color the message in a red font (to make
  618. the warning stand out from surrounding text).
  619. """
  620. text = coerce_string(text)
  621. if terminal_supports_colors(sys.stderr):
  622. text = ansi_wrap(text, color='red')
  623. auto_encode(sys.stderr, text + '\n', *args, **kw)
  624. # Define aliases for backwards compatibility.
  625. define_aliases(
  626. module_name=__name__,
  627. # In humanfriendly 1.31 the find_meta_variables() and format_usage()
  628. # functions were extracted to the new module humanfriendly.usage.
  629. find_meta_variables='humanfriendly.usage.find_meta_variables',
  630. format_usage='humanfriendly.usage.format_usage',
  631. # In humanfriendly 8.0 the html_to_ansi() function and HTMLConverter
  632. # class were extracted to the new module humanfriendly.terminal.html.
  633. html_to_ansi='humanfriendly.terminal.html.html_to_ansi',
  634. HTMLConverter='humanfriendly.terminal.html.HTMLConverter',
  635. )