README.rst 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. .. image:: https://img.shields.io/pypi/v/colorama.svg
  2. :target: https://pypi.org/project/colorama/
  3. :alt: Latest Version
  4. .. image:: https://img.shields.io/pypi/pyversions/colorama.svg
  5. :target: https://pypi.org/project/colorama/
  6. :alt: Supported Python versions
  7. .. image:: https://github.com/tartley/colorama/actions/workflows/test.yml/badge.svg
  8. :target: https://github.com/tartley/colorama/actions/workflows/test.yml
  9. :alt: Build Status
  10. Colorama
  11. ========
  12. Makes ANSI escape character sequences (for producing colored terminal text and
  13. cursor positioning) work under MS Windows.
  14. .. |donate| image:: https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif
  15. :target: https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=2MZ9D2GMLYCUJ&item_name=Colorama&currency_code=USD
  16. :alt: Donate with Paypal
  17. `PyPI for releases <https://pypi.org/project/colorama/>`_ |
  18. `Github for source <https://github.com/tartley/colorama>`_ |
  19. `Colorama for enterprise on Tidelift <https://github.com/tartley/colorama/blob/master/ENTERPRISE.md>`_
  20. If you find Colorama useful, please |donate| to the authors. Thank you!
  21. Installation
  22. ------------
  23. Tested on CPython 2.7, 3.7, 3.8, 3.9 and 3.10 and Pypy 2.7 and 3.8.
  24. No requirements other than the standard library.
  25. .. code-block:: bash
  26. pip install colorama
  27. # or
  28. conda install -c anaconda colorama
  29. Description
  30. -----------
  31. ANSI escape character sequences have long been used to produce colored terminal
  32. text and cursor positioning on Unix and Macs. Colorama makes this work on
  33. Windows, too, by wrapping ``stdout``, stripping ANSI sequences it finds (which
  34. would appear as gobbledygook in the output), and converting them into the
  35. appropriate win32 calls to modify the state of the terminal. On other platforms,
  36. Colorama does nothing.
  37. This has the upshot of providing a simple cross-platform API for printing
  38. colored terminal text from Python, and has the happy side-effect that existing
  39. applications or libraries which use ANSI sequences to produce colored output on
  40. Linux or Macs can now also work on Windows, simply by calling
  41. ``colorama.just_fix_windows_console()`` (since v0.4.6) or ``colorama.init()``
  42. (all versions, but may have other side-effects – see below).
  43. An alternative approach is to install ``ansi.sys`` on Windows machines, which
  44. provides the same behaviour for all applications running in terminals. Colorama
  45. is intended for situations where that isn't easy (e.g., maybe your app doesn't
  46. have an installer.)
  47. Demo scripts in the source code repository print some colored text using
  48. ANSI sequences. Compare their output under Gnome-terminal's built in ANSI
  49. handling, versus on Windows Command-Prompt using Colorama:
  50. .. image:: https://github.com/tartley/colorama/raw/master/screenshots/ubuntu-demo.png
  51. :width: 661
  52. :height: 357
  53. :alt: ANSI sequences on Ubuntu under gnome-terminal.
  54. .. image:: https://github.com/tartley/colorama/raw/master/screenshots/windows-demo.png
  55. :width: 668
  56. :height: 325
  57. :alt: Same ANSI sequences on Windows, using Colorama.
  58. These screenshots show that, on Windows, Colorama does not support ANSI 'dim
  59. text'; it looks the same as 'normal text'.
  60. Usage
  61. -----
  62. Initialisation
  63. ..............
  64. If the only thing you want from Colorama is to get ANSI escapes to work on
  65. Windows, then run:
  66. .. code-block:: python
  67. from colorama import just_fix_windows_console
  68. just_fix_windows_console()
  69. If you're on a recent version of Windows 10 or better, and your stdout/stderr
  70. are pointing to a Windows console, then this will flip the magic configuration
  71. switch to enable Windows' built-in ANSI support.
  72. If you're on an older version of Windows, and your stdout/stderr are pointing to
  73. a Windows console, then this will wrap ``sys.stdout`` and/or ``sys.stderr`` in a
  74. magic file object that intercepts ANSI escape sequences and issues the
  75. appropriate Win32 calls to emulate them.
  76. In all other circumstances, it does nothing whatsoever. Basically the idea is
  77. that this makes Windows act like Unix with respect to ANSI escape handling.
  78. It's safe to call this function multiple times. It's safe to call this function
  79. on non-Windows platforms, but it won't do anything. It's safe to call this
  80. function when one or both of your stdout/stderr are redirected to a file – it
  81. won't do anything to those streams.
  82. Alternatively, you can use the older interface with more features (but also more
  83. potential footguns):
  84. .. code-block:: python
  85. from colorama import init
  86. init()
  87. This does the same thing as ``just_fix_windows_console``, except for the
  88. following differences:
  89. - It's not safe to call ``init`` multiple times; you can end up with multiple
  90. layers of wrapping and broken ANSI support.
  91. - Colorama will apply a heuristic to guess whether stdout/stderr support ANSI,
  92. and if it thinks they don't, then it will wrap ``sys.stdout`` and
  93. ``sys.stderr`` in a magic file object that strips out ANSI escape sequences
  94. before printing them. This happens on all platforms, and can be convenient if
  95. you want to write your code to emit ANSI escape sequences unconditionally, and
  96. let Colorama decide whether they should actually be output. But note that
  97. Colorama's heuristic is not particularly clever.
  98. - ``init`` also accepts explicit keyword args to enable/disable various
  99. functionality – see below.
  100. To stop using Colorama before your program exits, simply call ``deinit()``.
  101. This will restore ``stdout`` and ``stderr`` to their original values, so that
  102. Colorama is disabled. To resume using Colorama again, call ``reinit()``; it is
  103. cheaper than calling ``init()`` again (but does the same thing).
  104. Most users should depend on ``colorama >= 0.4.6``, and use
  105. ``just_fix_windows_console``. The old ``init`` interface will be supported
  106. indefinitely for backwards compatibility, but we don't plan to fix any issues
  107. with it, also for backwards compatibility.
  108. Colored Output
  109. ..............
  110. Cross-platform printing of colored text can then be done using Colorama's
  111. constant shorthand for ANSI escape sequences. These are deliberately
  112. rudimentary, see below.
  113. .. code-block:: python
  114. from colorama import Fore, Back, Style
  115. print(Fore.RED + 'some red text')
  116. print(Back.GREEN + 'and with a green background')
  117. print(Style.DIM + 'and in dim text')
  118. print(Style.RESET_ALL)
  119. print('back to normal now')
  120. ...or simply by manually printing ANSI sequences from your own code:
  121. .. code-block:: python
  122. print('\033[31m' + 'some red text')
  123. print('\033[39m') # and reset to default color
  124. ...or, Colorama can be used in conjunction with existing ANSI libraries
  125. such as the venerable `Termcolor <https://pypi.org/project/termcolor/>`_
  126. the fabulous `Blessings <https://pypi.org/project/blessings/>`_,
  127. or the incredible `_Rich <https://pypi.org/project/rich/>`_.
  128. If you wish Colorama's Fore, Back and Style constants were more capable,
  129. then consider using one of the above highly capable libraries to generate
  130. colors, etc, and use Colorama just for its primary purpose: to convert
  131. those ANSI sequences to also work on Windows:
  132. SIMILARLY, do not send PRs adding the generation of new ANSI types to Colorama.
  133. We are only interested in converting ANSI codes to win32 API calls, not
  134. shortcuts like the above to generate ANSI characters.
  135. .. code-block:: python
  136. from colorama import just_fix_windows_console
  137. from termcolor import colored
  138. # use Colorama to make Termcolor work on Windows too
  139. just_fix_windows_console()
  140. # then use Termcolor for all colored text output
  141. print(colored('Hello, World!', 'green', 'on_red'))
  142. Available formatting constants are::
  143. Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
  144. Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
  145. Style: DIM, NORMAL, BRIGHT, RESET_ALL
  146. ``Style.RESET_ALL`` resets foreground, background, and brightness. Colorama will
  147. perform this reset automatically on program exit.
  148. These are fairly well supported, but not part of the standard::
  149. Fore: LIGHTBLACK_EX, LIGHTRED_EX, LIGHTGREEN_EX, LIGHTYELLOW_EX, LIGHTBLUE_EX, LIGHTMAGENTA_EX, LIGHTCYAN_EX, LIGHTWHITE_EX
  150. Back: LIGHTBLACK_EX, LIGHTRED_EX, LIGHTGREEN_EX, LIGHTYELLOW_EX, LIGHTBLUE_EX, LIGHTMAGENTA_EX, LIGHTCYAN_EX, LIGHTWHITE_EX
  151. Cursor Positioning
  152. ..................
  153. ANSI codes to reposition the cursor are supported. See ``demos/demo06.py`` for
  154. an example of how to generate them.
  155. Init Keyword Args
  156. .................
  157. ``init()`` accepts some ``**kwargs`` to override default behaviour.
  158. init(autoreset=False):
  159. If you find yourself repeatedly sending reset sequences to turn off color
  160. changes at the end of every print, then ``init(autoreset=True)`` will
  161. automate that:
  162. .. code-block:: python
  163. from colorama import init
  164. init(autoreset=True)
  165. print(Fore.RED + 'some red text')
  166. print('automatically back to default color again')
  167. init(strip=None):
  168. Pass ``True`` or ``False`` to override whether ANSI codes should be
  169. stripped from the output. The default behaviour is to strip if on Windows
  170. or if output is redirected (not a tty).
  171. init(convert=None):
  172. Pass ``True`` or ``False`` to override whether to convert ANSI codes in the
  173. output into win32 calls. The default behaviour is to convert if on Windows
  174. and output is to a tty (terminal).
  175. init(wrap=True):
  176. On Windows, Colorama works by replacing ``sys.stdout`` and ``sys.stderr``
  177. with proxy objects, which override the ``.write()`` method to do their work.
  178. If this wrapping causes you problems, then this can be disabled by passing
  179. ``init(wrap=False)``. The default behaviour is to wrap if ``autoreset`` or
  180. ``strip`` or ``convert`` are True.
  181. When wrapping is disabled, colored printing on non-Windows platforms will
  182. continue to work as normal. To do cross-platform colored output, you can
  183. use Colorama's ``AnsiToWin32`` proxy directly:
  184. .. code-block:: python
  185. import sys
  186. from colorama import init, AnsiToWin32
  187. init(wrap=False)
  188. stream = AnsiToWin32(sys.stderr).stream
  189. # Python 2
  190. print >>stream, Fore.BLUE + 'blue text on stderr'
  191. # Python 3
  192. print(Fore.BLUE + 'blue text on stderr', file=stream)
  193. Recognised ANSI Sequences
  194. .........................
  195. ANSI sequences generally take the form::
  196. ESC [ <param> ; <param> ... <command>
  197. Where ``<param>`` is an integer, and ``<command>`` is a single letter. Zero or
  198. more params are passed to a ``<command>``. If no params are passed, it is
  199. generally synonymous with passing a single zero. No spaces exist in the
  200. sequence; they have been inserted here simply to read more easily.
  201. The only ANSI sequences that Colorama converts into win32 calls are::
  202. ESC [ 0 m # reset all (colors and brightness)
  203. ESC [ 1 m # bright
  204. ESC [ 2 m # dim (looks same as normal brightness)
  205. ESC [ 22 m # normal brightness
  206. # FOREGROUND:
  207. ESC [ 30 m # black
  208. ESC [ 31 m # red
  209. ESC [ 32 m # green
  210. ESC [ 33 m # yellow
  211. ESC [ 34 m # blue
  212. ESC [ 35 m # magenta
  213. ESC [ 36 m # cyan
  214. ESC [ 37 m # white
  215. ESC [ 39 m # reset
  216. # BACKGROUND
  217. ESC [ 40 m # black
  218. ESC [ 41 m # red
  219. ESC [ 42 m # green
  220. ESC [ 43 m # yellow
  221. ESC [ 44 m # blue
  222. ESC [ 45 m # magenta
  223. ESC [ 46 m # cyan
  224. ESC [ 47 m # white
  225. ESC [ 49 m # reset
  226. # cursor positioning
  227. ESC [ y;x H # position cursor at x across, y down
  228. ESC [ y;x f # position cursor at x across, y down
  229. ESC [ n A # move cursor n lines up
  230. ESC [ n B # move cursor n lines down
  231. ESC [ n C # move cursor n characters forward
  232. ESC [ n D # move cursor n characters backward
  233. # clear the screen
  234. ESC [ mode J # clear the screen
  235. # clear the line
  236. ESC [ mode K # clear the line
  237. Multiple numeric params to the ``'m'`` command can be combined into a single
  238. sequence::
  239. ESC [ 36 ; 45 ; 1 m # bright cyan text on magenta background
  240. All other ANSI sequences of the form ``ESC [ <param> ; <param> ... <command>``
  241. are silently stripped from the output on Windows.
  242. Any other form of ANSI sequence, such as single-character codes or alternative
  243. initial characters, are not recognised or stripped. It would be cool to add
  244. them though. Let me know if it would be useful for you, via the Issues on
  245. GitHub.
  246. Status & Known Problems
  247. -----------------------
  248. I've personally only tested it on Windows XP (CMD, Console2), Ubuntu
  249. (gnome-terminal, xterm), and OS X.
  250. Some valid ANSI sequences aren't recognised.
  251. If you're hacking on the code, see `README-hacking.md`_. ESPECIALLY, see the
  252. explanation there of why we do not want PRs that allow Colorama to generate new
  253. types of ANSI codes.
  254. See outstanding issues and wish-list:
  255. https://github.com/tartley/colorama/issues
  256. If anything doesn't work for you, or doesn't do what you expected or hoped for,
  257. I'd love to hear about it on that issues list, would be delighted by patches,
  258. and would be happy to grant commit access to anyone who submits a working patch
  259. or two.
  260. .. _README-hacking.md: README-hacking.md
  261. License
  262. -------
  263. Copyright Jonathan Hartley & Arnon Yaari, 2013-2020. BSD 3-Clause license; see
  264. LICENSE file.
  265. Professional support
  266. --------------------
  267. .. |tideliftlogo| image:: https://cdn2.hubspot.net/hubfs/4008838/website/logos/logos_for_download/Tidelift_primary-shorthand-logo.png
  268. :alt: Tidelift
  269. :target: https://tidelift.com/subscription/pkg/pypi-colorama?utm_source=pypi-colorama&utm_medium=referral&utm_campaign=readme
  270. .. list-table::
  271. :widths: 10 100
  272. * - |tideliftlogo|
  273. - Professional support for colorama is available as part of the
  274. `Tidelift Subscription`_.
  275. Tidelift gives software development teams a single source for purchasing
  276. and maintaining their software, with professional grade assurances from
  277. the experts who know it best, while seamlessly integrating with existing
  278. tools.
  279. .. _Tidelift Subscription: https://tidelift.com/subscription/pkg/pypi-colorama?utm_source=pypi-colorama&utm_medium=referral&utm_campaign=readme
  280. Thanks
  281. ------
  282. See the CHANGELOG for more thanks!
  283. * Marc Schlaich (schlamar) for a ``setup.py`` fix for Python2.5.
  284. * Marc Abramowitz, reported & fixed a crash on exit with closed ``stdout``,
  285. providing a solution to issue #7's setuptools/distutils debate,
  286. and other fixes.
  287. * User 'eryksun', for guidance on correctly instantiating ``ctypes.windll``.
  288. * Matthew McCormick for politely pointing out a longstanding crash on non-Win.
  289. * Ben Hoyt, for a magnificent fix under 64-bit Windows.
  290. * Jesse at Empty Square for submitting a fix for examples in the README.
  291. * User 'jamessp', an observant documentation fix for cursor positioning.
  292. * User 'vaal1239', Dave Mckee & Lackner Kristof for a tiny but much-needed Win7
  293. fix.
  294. * Julien Stuyck, for wisely suggesting Python3 compatible updates to README.
  295. * Daniel Griffith for multiple fabulous patches.
  296. * Oscar Lesta for a valuable fix to stop ANSI chars being sent to non-tty
  297. output.
  298. * Roger Binns, for many suggestions, valuable feedback, & bug reports.
  299. * Tim Golden for thought and much appreciated feedback on the initial idea.
  300. * User 'Zearin' for updates to the README file.
  301. * John Szakmeister for adding support for light colors
  302. * Charles Merriam for adding documentation to demos
  303. * Jurko for a fix on 64-bit Windows CPython2.5 w/o ctypes
  304. * Florian Bruhin for a fix when stdout or stderr are None
  305. * Thomas Weininger for fixing ValueError on Windows
  306. * Remi Rampin for better Github integration and fixes to the README file
  307. * Simeon Visser for closing a file handle using 'with' and updating classifiers
  308. to include Python 3.3 and 3.4
  309. * Andy Neff for fixing RESET of LIGHT_EX colors.
  310. * Jonathan Hartley for the initial idea and implementation.