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.

381 lines
21 KiB

4 years ago
  1. Metadata-Version: 2.1
  2. Name: wasabi
  3. Version: 0.6.0
  4. Summary: A lightweight console printing and formatting toolkit
  5. Home-page: https://ines.io
  6. Author: Ines Montani
  7. Author-email: ines@explosion.ai
  8. License: MIT
  9. Platform: UNKNOWN
  10. Description-Content-Type: text/markdown
  11. # wasabi: A lightweight console printing and formatting toolkit
  12. Over the years, I've written countless implementations of coloring and
  13. formatting utilities to output messages in our libraries like
  14. [spaCy](https://spacy.io), [Thinc](https://github.com/explosion/thinc) and
  15. [Prodigy](https://prodi.gy). While there are many other great open-source
  16. options, I've always ended up wanting something slightly different or slightly
  17. custom.
  18. This package is still a work in progress and aims to bundle those utilities in a
  19. standardised way so they can be shared across our other projects. It's super
  20. lightweight, has zero dependencies and works across Python 2 and 3.
  21. [![Azure Pipelines](https://img.shields.io/azure-devops/build/explosion-ai/public/1/master.svg?logo=azure-pipelines&style=flat-square)](https://dev.azure.com/explosion-ai/public/_build?definitionId=1)
  22. [![PyPi](https://img.shields.io/pypi/v/wasabi.svg?style=flat-square&logo=pypi&logoColor=white)](https://pypi.python.org/pypi/wasabi)
  23. [![conda](https://img.shields.io/conda/vn/conda-forge/wasabi.svg?style=flat-square&logo=conda-forge/logoColor=white)](https://anaconda.org/conda-forge/wasabi)
  24. [![GitHub](https://img.shields.io/github/release/ines/wasabi/all.svg?style=flat-square&logo=github)](https://github.com/ines/wasabi)
  25. [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg?style=flat-square)](https://github.com/ambv/black)
  26. <img width="609" src="https://user-images.githubusercontent.com/13643239/48663861-8c9ea000-ea96-11e8-8b04-d120c52276a8.png">
  27. ## 💬 FAQ
  28. ### Are you going to add more features?
  29. Yes, there's still a few of helpers and features to port over. However, the new
  30. features will be heavily biased by what we (think we) need. I always appreciate
  31. pull requests to improve the existing functionality – but I want to keep this
  32. library as simple, lightweight and specific as possible.
  33. ### Can I use this for my projects?
  34. Sure, if you like it, feel free to adopt it! Just keep in mind that the package
  35. is very specific and not intended to be a full-featured and fully customisable
  36. formatting library. If that's what you're looking for, you might want to try
  37. other packages – for example, [`colored`](https://pypi.org/project/colored/),
  38. [`crayons`](https://github.com/kennethreitz/crayons),
  39. [`colorful`](https://github.com/timofurrer/colorful),
  40. [`tabulate`](https://bitbucket.org/astanin/python-tabulate),
  41. [`console`](https://github.com/mixmastamyk/console) or
  42. [`py-term`](https://github.com/gravmatt/py-term), to name a few.
  43. ### Why `wasabi`?
  44. I was looking for a short and descriptive name, but everything was already
  45. taken. So I ended up naming this package after one of my rats, Wasabi. 🐀
  46. ## ⌛️ Installation
  47. ```bash
  48. pip install wasabi
  49. ```
  50. ## 🎛 API
  51. ### <kbd>function</kbd> `msg`
  52. An instance of `Printer`, initialized with the default config. Useful as a quick
  53. shortcut if you don't need to customize initialization.
  54. ```python
  55. from wasabi import msg
  56. msg.good("Success!")
  57. ```
  58. ### <kbd>class</kbd> `Printer`
  59. #### <kbd>method</kbd> `Printer.__init__`
  60. ```python
  61. from wasabi import Printer
  62. msg = Printer()
  63. ```
  64. | Argument | Type | Description | Default |
  65. | ----------------- | --------- | ------------------------------------------------------------- | ------------- |
  66. | `pretty` | bool | Pretty-print output with colors and icons. | `True` |
  67. | `no_print` | bool | Don't actually print, just return. | `False` |
  68. | `colors` | dict | Add or overwrite color values, names mapped to `0`-`256`. | `None` |
  69. | `icons` | dict | Add or overwrite icon. Name mapped to unicode. | `None` |
  70. | `line_max` | int | Maximum line length (for divider). | `80` |
  71. | `animation` | unicode | Steps of loading animation for `Printer.loading`. | `"⠙⠹⠸⠼⠴⠦⠧⠇⠏"` |
  72. | `animation_ascii` | unicode | Alternative animation for ASCII terminals. | `"\|/-\\"` |
  73. | `hide_animation` | bool | Don't display animation, e.g. for logs. | `False` |
  74. | `ignore_warnings` | bool | Don't output messages of type `MESSAGE.WARN`. | `False` |
  75. | `env_prefix` | unicode | Prefix for environment variables, e.g. `WASABI_LOG_FRIENDLY`. | `"WASABI"` |
  76. | `timestamp` | bool | Add timestamp before output. | `False` |
  77. | **RETURNS** | `Printer` | The initialized printer. | - |
  78. #### <kbd>method</kbd> `Printer.text`
  79. ```python
  80. msg = Printer()
  81. msg.text("Hello world!")
  82. ```
  83. | Argument | Type | Description | Default |
  84. | ---------- | -------------- | ---------------------------------------------------------------------------------------------------------------------- | ------- |
  85. | `title` | unicode | The main text to print. | `""` |
  86. | `text` | unicode | Optional additional text to print. | `""` |
  87. | `color` |  unicode / int | Color name or value. | `None` |
  88. | `icon` | unicode | Name of icon to add. | `None` |
  89. | `show` | bool | Whether to print or not. Can be used to only output messages under certain condition, e.g. if `--verbose` flag is set. | `True` |
  90. | `spaced` | bool | Whether to add newlines around the output. | `False` |
  91. | `no_print` | bool | Don't actually print, just return. Overwrites global setting. | `False` |
  92. | `exits` | int | If set, perform a system exit with the given code after printing. | `None` |
  93. #### <kbd>method</kbd> `Printer.good`, `Printer.fail`, `Printer.warn`, `Printer.info`
  94. Print special formatted messages.
  95. ```python
  96. msg = Printer()
  97. msg.good("Success")
  98. msg.fail("Error")
  99. msg.warn("Warning")
  100. msg.info("Info")
  101. ```
  102. | Argument | Type | Description | Default |
  103. | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------- | ------- |
  104. | `title` | unicode | The main text to print. | `""` |
  105. | `text` | unicode | Optional additional text to print. | `""` |
  106. | `show` | bool | Whether to print or not. Can be used to only output messages under certain condition, e.g. if `--verbose` flag is set. | `True` |
  107. | `exits` | int | If set, perform a system exit with the given code after printing. | `None` |
  108. #### <kbd>method</kbd> `Printer.divider`
  109. Print a formatted divider.
  110. ```python
  111. msg = Printer()
  112. msg.divider("Heading")
  113. ```
  114. | Argument | Type | Description | Default |
  115. | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------- | ------- |
  116. | `text` | unicode | Headline text. If empty, only the line is printed. | `""` |
  117. | `char` | unicode | Single line character to repeat. | `"="` |
  118. | `show` | bool | Whether to print or not. Can be used to only output messages under certain condition, e.g. if `--verbose` flag is set. | `True` |
  119. | `icon` | unicode | Optional icon to use with title. | `None` |
  120. #### <kbd>contextmanager</kbd> `Printer.loading`
  121. ```python
  122. msg = Printer()
  123. with msg.loading("Loading..."):
  124. # Do something here that takes longer
  125. time.sleep(10)
  126. msg.good("Successfully loaded something!")
  127. ```
  128. | Argument | Type | Description | Default |
  129. | -------- | ------- | ---------------------------------- | ------- |
  130. | `text` | unicode | The text to display while loading. | `""` |
  131. #### <kbd>method</kbd> `Printer.table`, `Printer.row`
  132. See [Tables](#tables).
  133. #### <kbd>property</kbd> `Printer.counts`
  134. Get the counts of how often the special printers were fired, e.g.
  135. `MESSAGES.GOOD`. Can be used to print an overview like "X warnings"
  136. ```python
  137. msg = Printer()
  138. msg.good("Success")
  139. msg.fail("Error")
  140. msg.warn("Error")
  141. print(msg.counts)
  142. # Counter({'good': 1, 'fail': 2, 'warn': 0, 'info': 0})
  143. ```
  144. | Argument | Type | Description |
  145. | ----------- | --------- | ---------------------------------------------------- |
  146. | **RETURNS** | `Counter` | The counts for the individual special message types. |
  147. ### Tables
  148. #### <kbd>function</kbd> `table`
  149. Lightweight helper to format tabular data.
  150. ```python
  151. from wasabi import table
  152. data = [("a1", "a2", "a3"), ("b1", "b2", "b3")]
  153. header = ("Column 1", "Column 2", "Column 3")
  154. widths = (8, 9, 10)
  155. aligns = ("r", "c", "l")
  156. formatted = table(data, header=header, divider=True, widths=widths, aligns=aligns)
  157. ```
  158. ```
  159. Column 1 Column 2 Column 3
  160. -------- --------- ----------
  161. a1 a2 a3
  162. b1 b2 b3
  163. ```
  164. | Argument | Type | Description | Default |
  165. | ----------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | -------- |
  166. | `data` | iterable / dict | The data to render. Either a list of lists (one per row) or a dict for two-column tables. | |
  167. | `header` | iterable | Optional header columns. | `None` |
  168. | `footer` | iterable | Optional footer columns. | `None` |
  169. | `divider` | bool | Show a divider line between header/footer and body. | `False` |
  170. | `widths` | iterable / `"auto"` | Column widths in order. If `"auto"`, widths will be calculated automatically based on the largest value. | `"auto"` |
  171. | `max_col` | int | Maximum column width. | `30` |
  172. | `spacing` | int | Number of spaces between columns. | `3` |
  173. | `aligns` | iterable / unicode | Columns alignments in order. `"l"` (left, default), `"r"` (right) or `"c"` (center). If If a string, value is used for all columns. | `None` |
  174. | `multiline` | bool | If a cell value is a list of a tuple, render it on multiple lines, with one value per line. | `False` |
  175. | **RETURNS** | unicode | The formatted table. | |
  176. #### <kbd>function</kbd> `row`
  177. ```python
  178. from wasabi import row
  179. data = ("a1", "a2", "a3")
  180. formatted = row(data)
  181. ```
  182. ```
  183. a1 a2 a3
  184. ```
  185. | Argument | Type | Description | Default |
  186. | ----------- | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |
  187. | `data` | iterable | The individual columns to format. | |
  188. | `widths` | iterable / int / `"auto"` | Column widths, either one integer for all columns or an iterable of values. If "auto", widths will be calculated automatically based on the largest value. | `"auto"` |
  189. | `spacing` | int | Number of spaces between columns. | `3` |
  190. | `aligns` | iterable | Columns alignments in order. `"l"` (left), `"r"` (right) or `"c"` (center). | `None` |
  191. | **RETURNS** | unicode | The formatted row. | |
  192. ### <kbd>class</kbd> `TracebackPrinter`
  193. Helper to output custom formatted tracebacks and error messages. Currently used
  194. in [Thinc](https://github.com/explosion/thinc).
  195. #### <kbd>method</kbd> `TracebackPrinter.__init__`
  196. Initialize a traceback printer.
  197. ```python
  198. from wasabi import TracebackPrinter
  199. tb = TracebackPrinter(tb_base="thinc", tb_exclude=("check.py",))
  200. ```
  201. | Argument | Type | Description | Default |
  202. | ----------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------- |
  203. | `color_error` | unicode / int | Color name or code for errors (passed to `color` helper). | `"red"` |
  204. | `color_tb` | unicode / int | Color name or code for traceback headline (passed to `color` helper). | `"blue"` |
  205. | `color_highlight` | unicode / int | Color name or code for highlighted text (passed to `color` helper). | `"yellow"` |
  206. | `indent` | int | Number of spaces to use for indentation. | `2` |
  207. | `tb_base` | unicode | Name of directory to use to show relative paths. For example, `"thinc"` will look for the last occurence of `"/thinc/"` in a path and only show path to the right of it. | `None` |
  208. | `tb_exclude` | tuple | List of filenames to exclude from traceback. | `tuple()` |
  209. | **RETURNS** | `TracebackPrinter` | The traceback printer. | |
  210. #### <kbd>method</kbd> `TracebackPrinter.__call__`
  211. Output custom formatted tracebacks and errors.
  212. ```python
  213. from wasabi import TracebackPrinter
  214. import traceback
  215. tb = TracebackPrinter(tb_base="thinc", tb_exclude=("check.py",))
  216. error = tb("Some error", "Error description", highlight="kwargs", tb=traceback.extract_stack())
  217. raise ValueError(error)
  218. ```
  219. ```
  220. Some error
  221. Some error description
  222. Traceback:
  223. ├─ <lambda> [61] in .env/lib/python3.6/site-packages/pluggy/manager.py
  224. ├─── _multicall [187] in .env/lib/python3.6/site-packages/pluggy/callers.py
  225. └───── pytest_fixture_setup [969] in .env/lib/python3.6/site-packages/_pytest/fixtures.py
  226. >>> result = call_fixture_func(fixturefunc, request, kwargs)
  227. ```
  228. | Argument | Type | Description | Default |
  229. | ----------- | -------- | ------------------------------------------------------------------------------------------ | ------- |
  230. | `title` | unicode | The message title. | |
  231. | `*texts` | unicode | Optional texts to print (one per line). | |
  232. | `highlight` | unicode | Optional sequence to highlight in the traceback, e.g. the bad value that caused the error. | `False` |
  233. | `tb` | iterable | The traceback, e.g. generated by `traceback.extract_stack()`. | `None` |
  234. | **RETURNS** | unicode | The formatted traceback. Can be printed or raised by custom exception. | |
  235. ### Utilities
  236. #### <kbd>function</kbd> `color`
  237. ```python
  238. from wasabi import color
  239. formatted = color("This is a text", fg="white", bg="green", bold=True)
  240. ```
  241. | Argument | Type | Description | Default |
  242. | ----------- | ------------- | --------------------------------------------- | ------- |
  243. | `text` | unicode | The text to be formatted. | - |
  244. | `fg` | unicode / int | Foreground color. String name or `0` - `256`. | `None` |
  245. | `bg` | unicode / int | Background color. String name or `0` - `256`. | `None` |
  246. | `bold` | bool | Format the text in bold. | `False` |
  247. | **RETURNS** | unicode | The formatted string. | |
  248. #### <kbd>function</kbd> `wrap`
  249. ```python
  250. from wasabi import wrap
  251. wrapped = wrap("Hello world, this is a text.", indent=2)
  252. ```
  253. | Argument | Type | Description | Default |
  254. | ----------- | ------- | ------------------------------------------ | ------- |
  255. | `text` | unicode | The text to wrap. | - |
  256. | `wrap_max` | int | Maximum line width, including indentation. | `80` |
  257. | `indent` | int | Number of spaces used for indentation. | `4` |
  258. | **RETURNS** | unicode | The wrapped text with line breaks. | |
  259. #### <kbd>function</kbd> `diff_strings`
  260. ```python
  261. from wasabi import diff_strings
  262. diff = diff_strings("hello world!", "helloo world")
  263. ```
  264. | Argument | Type | Description | Default |
  265. | ----------- | ------------- | ---------------------------------------------------------------------------- | ------------------ |
  266. | `a` | unicode | The first string to diff. |
  267. | `b` | unicode | The second string to diff. |
  268. | `fg` | unicode / int | Foreground color. String name or `0` - `256`. | `"black"` |
  269. | `bg` | tuple | Background colors as `(insert, delete)` tuple of string name or `0` - `256`. | `("green", "red")` |
  270. | **RETURNS** | unicode | The formatted diff. | |
  271. ### Environment variables
  272. Wasabi also respects the following environment variables. The prefix can be
  273. customised on the `Printer` via the `env_prefix` argument. For example, setting
  274. `env_prefix="SPACY"` will expect the environment variable `SPACY_LOG_FRIENDLY`.
  275. | Name | Description |
  276. | ---------------------- | ------------------------------------------------------ |
  277. | `ANSI_COLORS_DISABLED` | Disable colors. |
  278. | `WASABI_LOG_FRIENDLY` | Make output nicer for logs (no colors, no animations). |
  279. | `WASABI_NO_PRETTY` | Disable pretty printing, e.g. colors and icons. |
  280. ## 🔔 Run tests
  281. Fork or clone the repo, make sure you have `pytest` installed and then run it on
  282. the package directory. The tests are located in
  283. [`/wasabi/tests`](/wasabi/tests).
  284. ```bash
  285. pip install pytest
  286. cd wasabi
  287. python -m pytest wasabi
  288. ```