DESCRIPTION.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. .. image:: https://img.shields.io/pypi/v/colorama.svg
  2. :target: https://pypi.python.org/pypi/colorama/
  3. :alt: Latest Version
  4. .. image:: https://travis-ci.org/tartley/colorama.svg?branch=master
  5. :target: https://travis-ci.org/tartley/colorama
  6. :alt: Build Status
  7. Download and docs:
  8. http://pypi.python.org/pypi/colorama
  9. Source code & Development:
  10. https://github.com/tartley/colorama
  11. Description
  12. ===========
  13. Makes ANSI escape character sequences (for producing colored terminal text and
  14. cursor positioning) work under MS Windows.
  15. ANSI escape character sequences have long been used to produce colored terminal
  16. text and cursor positioning on Unix and Macs. Colorama makes this work on
  17. Windows, too, by wrapping ``stdout``, stripping ANSI sequences it finds (which
  18. would appear as gobbledygook in the output), and converting them into the
  19. appropriate win32 calls to modify the state of the terminal. On other platforms,
  20. Colorama does nothing.
  21. Colorama also provides some shortcuts to help generate ANSI sequences
  22. but works fine in conjunction with any other ANSI sequence generation library,
  23. such as the venerable Termcolor (http://pypi.python.org/pypi/termcolor)
  24. or the fabulous Blessings (https://pypi.python.org/pypi/blessings).
  25. This has the upshot of providing a simple cross-platform API for printing
  26. colored terminal text from Python, and has the happy side-effect that existing
  27. applications or libraries which use ANSI sequences to produce colored output on
  28. Linux or Macs can now also work on Windows, simply by calling
  29. ``colorama.init()``.
  30. An alternative approach is to install ``ansi.sys`` on Windows machines, which
  31. provides the same behaviour for all applications running in terminals. Colorama
  32. is intended for situations where that isn't easy (e.g., maybe your app doesn't
  33. have an installer.)
  34. Demo scripts in the source code repository print some colored text using
  35. ANSI sequences. Compare their output under Gnome-terminal's built in ANSI
  36. handling, versus on Windows Command-Prompt using Colorama:
  37. .. image:: https://github.com/tartley/colorama/raw/master/screenshots/ubuntu-demo.png
  38. :width: 661
  39. :height: 357
  40. :alt: ANSI sequences on Ubuntu under gnome-terminal.
  41. .. image:: https://github.com/tartley/colorama/raw/master/screenshots/windows-demo.png
  42. :width: 668
  43. :height: 325
  44. :alt: Same ANSI sequences on Windows, using Colorama.
  45. These screengrabs show that, on Windows, Colorama does not support ANSI 'dim
  46. text'; it looks the same as 'normal text'.
  47. License
  48. =======
  49. Copyright Jonathan Hartley 2013. BSD 3-Clause license; see LICENSE file.
  50. Dependencies
  51. ============
  52. None, other than Python. Tested on Python 2.5.5, 2.6.5, 2.7, 3.1.2, 3.2, 3.3,
  53. 3.4 and 3.5.
  54. Usage
  55. =====
  56. Initialisation
  57. --------------
  58. Applications should initialise Colorama using:
  59. .. code-block:: python
  60. from colorama import init
  61. init()
  62. On Windows, calling ``init()`` will filter ANSI escape sequences out of any
  63. text sent to ``stdout`` or ``stderr``, and replace them with equivalent Win32
  64. calls.
  65. On other platforms, calling ``init()`` has no effect (unless you request other
  66. optional functionality; see "Init Keyword Args", below). By design, this permits
  67. applications to call ``init()`` unconditionally on all platforms, after which
  68. ANSI output should just work.
  69. To stop using colorama before your program exits, simply call ``deinit()``.
  70. This will restore ``stdout`` and ``stderr`` to their original values, so that
  71. Colorama is disabled. To resume using Colorama again, call ``reinit()``; it is
  72. cheaper to calling ``init()`` again (but does the same thing).
  73. Colored Output
  74. --------------
  75. Cross-platform printing of colored text can then be done using Colorama's
  76. constant shorthand for ANSI escape sequences:
  77. .. code-block:: python
  78. from colorama import Fore, Back, Style
  79. print(Fore.RED + 'some red text')
  80. print(Back.GREEN + 'and with a green background')
  81. print(Style.DIM + 'and in dim text')
  82. print(Style.RESET_ALL)
  83. print('back to normal now')
  84. ...or simply by manually printing ANSI sequences from your own code:
  85. .. code-block:: python
  86. print('\033[31m' + 'some red text')
  87. print('\033[30m') # and reset to default color
  88. ...or, Colorama can be used happily in conjunction with existing ANSI libraries
  89. such as Termcolor:
  90. .. code-block:: python
  91. from colorama import init
  92. from termcolor import colored
  93. # use Colorama to make Termcolor work on Windows too
  94. init()
  95. # then use Termcolor for all colored text output
  96. print(colored('Hello, World!', 'green', 'on_red'))
  97. Available formatting constants are::
  98. Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
  99. Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
  100. Style: DIM, NORMAL, BRIGHT, RESET_ALL
  101. ``Style.RESET_ALL`` resets foreground, background, and brightness. Colorama will
  102. perform this reset automatically on program exit.
  103. Cursor Positioning
  104. ------------------
  105. ANSI codes to reposition the cursor are supported. See ``demos/demo06.py`` for
  106. an example of how to generate them.
  107. Init Keyword Args
  108. -----------------
  109. ``init()`` accepts some ``**kwargs`` to override default behaviour.
  110. init(autoreset=False):
  111. If you find yourself repeatedly sending reset sequences to turn off color
  112. changes at the end of every print, then ``init(autoreset=True)`` will
  113. automate that:
  114. .. code-block:: python
  115. from colorama import init
  116. init(autoreset=True)
  117. print(Fore.RED + 'some red text')
  118. print('automatically back to default color again')
  119. init(strip=None):
  120. Pass ``True`` or ``False`` to override whether ansi codes should be
  121. stripped from the output. The default behaviour is to strip if on Windows
  122. or if output is redirected (not a tty).
  123. init(convert=None):
  124. Pass ``True`` or ``False`` to override whether to convert ANSI codes in the
  125. output into win32 calls. The default behaviour is to convert if on Windows
  126. and output is to a tty (terminal).
  127. init(wrap=True):
  128. On Windows, colorama works by replacing ``sys.stdout`` and ``sys.stderr``
  129. with proxy objects, which override the ``.write()`` method to do their work.
  130. If this wrapping causes you problems, then this can be disabled by passing
  131. ``init(wrap=False)``. The default behaviour is to wrap if ``autoreset`` or
  132. ``strip`` or ``convert`` are True.
  133. When wrapping is disabled, colored printing on non-Windows platforms will
  134. continue to work as normal. To do cross-platform colored output, you can
  135. use Colorama's ``AnsiToWin32`` proxy directly:
  136. .. code-block:: python
  137. import sys
  138. from colorama import init, AnsiToWin32
  139. init(wrap=False)
  140. stream = AnsiToWin32(sys.stderr).stream
  141. # Python 2
  142. print >>stream, Fore.BLUE + 'blue text on stderr'
  143. # Python 3
  144. print(Fore.BLUE + 'blue text on stderr', file=stream)
  145. Status & Known Problems
  146. =======================
  147. I've personally only tested it on Windows XP (CMD, Console2), Ubuntu
  148. (gnome-terminal, xterm), and OS X.
  149. Some presumably valid ANSI sequences aren't recognised (see details below),
  150. but to my knowledge nobody has yet complained about this. Puzzling.
  151. See outstanding issues and wishlist:
  152. https://github.com/tartley/colorama/issues
  153. If anything doesn't work for you, or doesn't do what you expected or hoped for,
  154. I'd love to hear about it on that issues list, would be delighted by patches,
  155. and would be happy to grant commit access to anyone who submits a working patch
  156. or two.
  157. Recognised ANSI Sequences
  158. =========================
  159. ANSI sequences generally take the form:
  160. ESC [ <param> ; <param> ... <command>
  161. Where ``<param>`` is an integer, and ``<command>`` is a single letter. Zero or
  162. more params are passed to a ``<command>``. If no params are passed, it is
  163. generally synonymous with passing a single zero. No spaces exist in the
  164. sequence; they have been inserted here simply to read more easily.
  165. The only ANSI sequences that colorama converts into win32 calls are::
  166. ESC [ 0 m # reset all (colors and brightness)
  167. ESC [ 1 m # bright
  168. ESC [ 2 m # dim (looks same as normal brightness)
  169. ESC [ 22 m # normal brightness
  170. # FOREGROUND:
  171. ESC [ 30 m # black
  172. ESC [ 31 m # red
  173. ESC [ 32 m # green
  174. ESC [ 33 m # yellow
  175. ESC [ 34 m # blue
  176. ESC [ 35 m # magenta
  177. ESC [ 36 m # cyan
  178. ESC [ 37 m # white
  179. ESC [ 39 m # reset
  180. # BACKGROUND
  181. ESC [ 40 m # black
  182. ESC [ 41 m # red
  183. ESC [ 42 m # green
  184. ESC [ 43 m # yellow
  185. ESC [ 44 m # blue
  186. ESC [ 45 m # magenta
  187. ESC [ 46 m # cyan
  188. ESC [ 47 m # white
  189. ESC [ 49 m # reset
  190. # cursor positioning
  191. ESC [ y;x H # position cursor at x across, y down
  192. ESC [ y;x f # position cursor at x across, y down
  193. ESC [ n A # move cursor n lines up
  194. ESC [ n B # move cursor n lines down
  195. ESC [ n C # move cursor n characters forward
  196. ESC [ n D # move cursor n characters backward
  197. # clear the screen
  198. ESC [ mode J # clear the screen
  199. # clear the line
  200. ESC [ mode K # clear the line
  201. Multiple numeric params to the ``'m'`` command can be combined into a single
  202. sequence::
  203. ESC [ 36 ; 45 ; 1 m # bright cyan text on magenta background
  204. All other ANSI sequences of the form ``ESC [ <param> ; <param> ... <command>``
  205. are silently stripped from the output on Windows.
  206. Any other form of ANSI sequence, such as single-character codes or alternative
  207. initial characters, are not recognised or stripped. It would be cool to add
  208. them though. Let me know if it would be useful for you, via the Issues on
  209. GitHub.
  210. Development
  211. ===========
  212. Help and fixes welcome!
  213. Running tests requires:
  214. - Michael Foord's ``mock`` module to be installed.
  215. - Tests are written using 2010-era updates to ``unittest``, and require
  216. Python 2.7 or greater, OR to have Michael Foord's ``unittest2`` module
  217. installed.
  218. To run tests::
  219. python -m unittest discover -p *_test.py
  220. This, like a few other handy commands, is captured in a ``Makefile``.
  221. If you use nose to run the tests, you must pass the ``-s`` flag; otherwise,
  222. ``nosetests`` applies its own proxy to ``stdout``, which confuses the unit
  223. tests.
  224. Thanks
  225. ======
  226. * Marc Schlaich (schlamar) for a ``setup.py`` fix for Python2.5.
  227. * Marc Abramowitz, reported & fixed a crash on exit with closed ``stdout``,
  228. providing a solution to issue #7's setuptools/distutils debate,
  229. and other fixes.
  230. * User 'eryksun', for guidance on correctly instantiating ``ctypes.windll``.
  231. * Matthew McCormick for politely pointing out a longstanding crash on non-Win.
  232. * Ben Hoyt, for a magnificent fix under 64-bit Windows.
  233. * Jesse at Empty Square for submitting a fix for examples in the README.
  234. * User 'jamessp', an observant documentation fix for cursor positioning.
  235. * User 'vaal1239', Dave Mckee & Lackner Kristof for a tiny but much-needed Win7
  236. fix.
  237. * Julien Stuyck, for wisely suggesting Python3 compatible updates to README.
  238. * Daniel Griffith for multiple fabulous patches.
  239. * Oscar Lesta for a valuable fix to stop ANSI chars being sent to non-tty
  240. output.
  241. * Roger Binns, for many suggestions, valuable feedback, & bug reports.
  242. * Tim Golden for thought and much appreciated feedback on the initial idea.
  243. * User 'Zearin' for updates to the README file.
  244. * John Szakmeister for adding support for light colors
  245. * Charles Merriam for adding documentation to demos
  246. * Jurko for a fix on 64-bit Windows CPython2.5 w/o ctypes
  247. * Florian Bruhin for a fix when stdout or stderr are None
  248. * Thomas Weininger for fixing ValueError on Windows
  249. * Remi Rampin for better Github integration and fixes to the README file
  250. * Simeon Visser for closing a file handle using 'with' and updating classifiers
  251. to include Python 3.3 and 3.4
  252. * Andy Neff for fixing RESET of LIGHT_EX colors.
  253. * Jonathan Hartley for the initial idea and implementation.