зеркало из https://github.com/mozilla/gecko-dev.git
Bug 1300577 - Upgrade blessings to version 1.6.1, r=gps
This also removes the metadata files (except for the LICENSE file) as those are not packaged in the binary wheel. MozReview-Commit-ID: 6Wzio21e8Ex --HG-- extra : rebase_source : 0de4c90ba5ee44f08d3cfa29791a9872bfb1aace
This commit is contained in:
Родитель
1254243529
Коммит
0840fce15d
|
@ -1,3 +0,0 @@
|
|||
include README.rst
|
||||
include LICENSE
|
||||
include tox.ini
|
|
@ -1,426 +0,0 @@
|
|||
Metadata-Version: 1.0
|
||||
Name: blessings
|
||||
Version: 1.3
|
||||
Summary: A thin, practical wrapper around terminal formatting, positioning, and more
|
||||
Home-page: https://github.com/erikrose/blessings
|
||||
Author: Erik Rose
|
||||
Author-email: erikrose@grinchcentral.com
|
||||
License: MIT
|
||||
Description: =========
|
||||
Blessings
|
||||
=========
|
||||
|
||||
Coding with Blessings looks like this... ::
|
||||
|
||||
from blessings import Terminal
|
||||
|
||||
t = Terminal()
|
||||
|
||||
print t.bold('Hi there!')
|
||||
print t.bold_red_on_bright_green('It hurts my eyes!')
|
||||
|
||||
with t.location(0, t.height - 1):
|
||||
print 'This is at the bottom.'
|
||||
|
||||
Or, for byte-level control, you can drop down and play with raw terminal
|
||||
capabilities::
|
||||
|
||||
print '{t.bold}All your {t.red}bold and red base{t.normal}'.format(t=t)
|
||||
print t.wingo(2)
|
||||
|
||||
The Pitch
|
||||
=========
|
||||
|
||||
Blessings lifts several of curses_' limiting assumptions, and it makes your
|
||||
code pretty, too:
|
||||
|
||||
* Use styles, color, and maybe a little positioning without clearing the whole
|
||||
screen first.
|
||||
* Leave more than one screenful of scrollback in the buffer after your program
|
||||
exits, like a well-behaved command-line app should.
|
||||
* Get rid of all those noisy, C-like calls to ``tigetstr`` and ``tparm``, so
|
||||
your code doesn't get crowded out by terminal bookkeeping.
|
||||
* Act intelligently when somebody redirects your output to a file, omitting the
|
||||
terminal control codes the user doesn't want to see (optional).
|
||||
|
||||
.. _curses: http://docs.python.org/library/curses.html
|
||||
|
||||
Before And After
|
||||
----------------
|
||||
|
||||
Without Blessings, this is how you'd print some underlined text at the bottom
|
||||
of the screen::
|
||||
|
||||
from curses import tigetstr, setupterm, tparm
|
||||
from fcntl import ioctl
|
||||
from os import isatty
|
||||
import struct
|
||||
import sys
|
||||
from termios import TIOCGWINSZ
|
||||
|
||||
# If we want to tolerate having our output piped to other commands or
|
||||
# files without crashing, we need to do all this branching:
|
||||
if hasattr(sys.stdout, 'fileno') and isatty(sys.stdout.fileno()):
|
||||
setupterm()
|
||||
sc = tigetstr('sc')
|
||||
cup = tigetstr('cup')
|
||||
rc = tigetstr('rc')
|
||||
underline = tigetstr('smul')
|
||||
normal = tigetstr('sgr0')
|
||||
else:
|
||||
sc = cup = rc = underline = normal = ''
|
||||
print sc # Save cursor position.
|
||||
if cup:
|
||||
# tigetnum('lines') doesn't always update promptly, hence this:
|
||||
height = struct.unpack('hhhh', ioctl(0, TIOCGWINSZ, '\000' * 8))[0]
|
||||
print tparm(cup, height - 1, 0) # Move cursor to bottom.
|
||||
print 'This is {under}underlined{normal}!'.format(under=underline,
|
||||
normal=normal)
|
||||
print rc # Restore cursor position.
|
||||
|
||||
Phew! That was long and full of incomprehensible trash! Let's try it again,
|
||||
this time with Blessings::
|
||||
|
||||
from blessings import Terminal
|
||||
|
||||
term = Terminal()
|
||||
with term.location(0, term.height - 1):
|
||||
print 'This is', term.underline('pretty!')
|
||||
|
||||
Much better.
|
||||
|
||||
What It Provides
|
||||
================
|
||||
|
||||
Blessings provides just one top-level object: ``Terminal``. Instantiating a
|
||||
``Terminal`` figures out whether you're on a terminal at all and, if so, does
|
||||
any necessary terminal setup. After that, you can proceed to ask it all sorts
|
||||
of things about the terminal. Terminal terminal terminal.
|
||||
|
||||
Simple Formatting
|
||||
-----------------
|
||||
|
||||
Lots of handy formatting codes ("capabilities" in low-level parlance) are
|
||||
available as attributes on a ``Terminal``. For example::
|
||||
|
||||
from blessings import Terminal
|
||||
|
||||
term = Terminal()
|
||||
print 'I am ' + term.bold + 'bold' + term.normal + '!'
|
||||
|
||||
You can also use them as wrappers so you don't have to say ``normal``
|
||||
afterward::
|
||||
|
||||
print 'I am', term.bold('bold') + '!'
|
||||
|
||||
Or, if you want fine-grained control while maintaining some semblance of
|
||||
brevity, you can combine it with Python's string formatting, which makes
|
||||
attributes easy to access::
|
||||
|
||||
print 'All your {t.red}base {t.underline}are belong to us{t.normal}'.format(t=term)
|
||||
|
||||
Simple capabilities of interest include...
|
||||
|
||||
* ``bold``
|
||||
* ``reverse``
|
||||
* ``underline``
|
||||
* ``no_underline`` (which turns off underlining)
|
||||
* ``blink``
|
||||
* ``normal`` (which turns off everything, even colors)
|
||||
* ``clear_eol`` (clear to the end of the line)
|
||||
* ``clear_bol`` (clear to beginning of line)
|
||||
* ``clear_eos`` (clear to end of screen)
|
||||
|
||||
Here are a few more which are less likely to work on all terminals:
|
||||
|
||||
* ``dim``
|
||||
* ``italic`` and ``no_italic``
|
||||
* ``shadow`` and ``no_shadow``
|
||||
* ``standout`` and ``no_standout``
|
||||
* ``subscript`` and ``no_subscript``
|
||||
* ``superscript`` and ``no_superscript``
|
||||
* ``flash`` (which flashes the screen once)
|
||||
|
||||
Note that, while the inverse of ``underline`` is ``no_underline``, the only way
|
||||
to turn off ``bold`` or ``reverse`` is ``normal``, which also cancels any
|
||||
custom colors. This is because there's no way to tell the terminal to undo
|
||||
certain pieces of formatting, even at the lowest level.
|
||||
|
||||
You might notice that the above aren't the typical incomprehensible terminfo
|
||||
capability names; we alias a few of the harder-to-remember ones for
|
||||
readability. However, you aren't limited to these: you can reference any
|
||||
string-returning capability listed on the `terminfo man page`_ by the name
|
||||
under the "Cap-name" column: for example, ``term.rum``.
|
||||
|
||||
.. _`terminfo man page`: http://www.manpagez.com/man/5/terminfo/
|
||||
|
||||
Color
|
||||
-----
|
||||
|
||||
16 colors, both foreground and background, are available as easy-to-remember
|
||||
attributes::
|
||||
|
||||
from blessings import Terminal
|
||||
|
||||
term = Terminal()
|
||||
print term.red + term.on_green + 'Red on green? Ick!' + term.normal
|
||||
print term.bright_red + term.on_bright_blue + 'This is even worse!' + term.normal
|
||||
|
||||
You can also call them as wrappers, which sets everything back to normal at the
|
||||
end::
|
||||
|
||||
print term.red_on_green('Red on green? Ick!')
|
||||
print term.yellow('I can barely see it.')
|
||||
|
||||
The available colors are...
|
||||
|
||||
* ``black``
|
||||
* ``red``
|
||||
* ``green``
|
||||
* ``yellow``
|
||||
* ``blue``
|
||||
* ``magenta``
|
||||
* ``cyan``
|
||||
* ``white``
|
||||
|
||||
You can set the background color instead of the foreground by prepending
|
||||
``on_``, as in ``on_blue``. There is also a ``bright`` version of each color:
|
||||
for example, ``on_bright_blue``.
|
||||
|
||||
There is also a numerical interface to colors, which takes an integer from
|
||||
0-15::
|
||||
|
||||
term.color(5) + 'Hello' + term.normal
|
||||
term.on_color(3) + 'Hello' + term.normal
|
||||
|
||||
term.color(5)('Hello')
|
||||
term.on_color(3)('Hello')
|
||||
|
||||
If some color is unsupported (for instance, if only the normal colors are
|
||||
available, not the bright ones), trying to use it will, on most terminals, have
|
||||
no effect: the foreground and background colors will stay as they were. You can
|
||||
get fancy and do different things depending on the supported colors by checking
|
||||
`number_of_colors`_.
|
||||
|
||||
.. _`number_of_colors`: http://packages.python.org/blessings/#blessings.Terminal.number_of_colors
|
||||
|
||||
Compound Formatting
|
||||
-------------------
|
||||
|
||||
If you want to do lots of crazy formatting all at once, you can just mash it
|
||||
all together::
|
||||
|
||||
from blessings import Terminal
|
||||
|
||||
term = Terminal()
|
||||
print term.bold_underline_green_on_yellow + 'Woo' + term.normal
|
||||
|
||||
Or you can use your newly coined attribute as a wrapper, which implicitly sets
|
||||
everything back to normal afterward::
|
||||
|
||||
print term.bold_underline_green_on_yellow('Woo')
|
||||
|
||||
This compound notation comes in handy if you want to allow users to customize
|
||||
the formatting of your app: just have them pass in a format specifier like
|
||||
"bold_green" on the command line, and do a quick ``getattr(term,
|
||||
that_option)('Your text')`` when you do your formatting.
|
||||
|
||||
I'd be remiss if I didn't credit couleur_, where I probably got the idea for
|
||||
all this mashing.
|
||||
|
||||
.. _couleur: http://pypi.python.org/pypi/couleur
|
||||
|
||||
Parametrized Capabilities
|
||||
-------------------------
|
||||
|
||||
Some capabilities take parameters. Rather than making you dig up ``tparm()``
|
||||
all the time, we simply make such capabilities into callable strings. You can
|
||||
pass the parameters right in::
|
||||
|
||||
from blessings import Terminal
|
||||
|
||||
term = Terminal()
|
||||
print term.move(10, 1)
|
||||
|
||||
Here are some of interest:
|
||||
|
||||
``move``
|
||||
Position the cursor elsewhere. Parameters are y coordinate, then x
|
||||
coordinate.
|
||||
``move_x``
|
||||
Move the cursor to the given column.
|
||||
``move_y``
|
||||
Move the cursor to the given row.
|
||||
|
||||
You can also reference any other string-returning capability listed on the
|
||||
`terminfo man page`_ by its name under the "Cap-name" column.
|
||||
|
||||
.. _`terminfo man page`: http://www.manpagez.com/man/5/terminfo/
|
||||
|
||||
Height and Width
|
||||
----------------
|
||||
|
||||
It's simple to get the height and width of the terminal, in characters::
|
||||
|
||||
from blessings import Terminal
|
||||
|
||||
term = Terminal()
|
||||
height = term.height
|
||||
width = term.width
|
||||
|
||||
These are newly updated each time you ask for them, so they're safe to use from
|
||||
SIGWINCH handlers.
|
||||
|
||||
Temporary Repositioning
|
||||
-----------------------
|
||||
|
||||
Sometimes you need to flit to a certain location, print something, and then
|
||||
return: for example, when updating a progress bar at the bottom of the screen.
|
||||
``Terminal`` provides a context manager for doing this concisely::
|
||||
|
||||
from blessings import Terminal
|
||||
|
||||
term = Terminal()
|
||||
with term.location(0, term.height - 1):
|
||||
print 'Here is the bottom.'
|
||||
print 'This is back where I came from.'
|
||||
|
||||
Parameters to ``location()`` are ``x`` and then ``y``, but you can also pass
|
||||
just one of them, leaving the other alone. For example... ::
|
||||
|
||||
with term.location(y=10):
|
||||
print 'We changed just the row.'
|
||||
|
||||
If you want to reposition permanently, see ``move``, in an example above.
|
||||
|
||||
Pipe Savvy
|
||||
----------
|
||||
|
||||
If your program isn't attached to a terminal, like if it's being piped to
|
||||
another command or redirected to a file, all the capability attributes on
|
||||
``Terminal`` will return empty strings. You'll get a nice-looking file without
|
||||
any formatting codes gumming up the works.
|
||||
|
||||
If you want to override this--like if you anticipate your program being piped
|
||||
through ``less -r``, which handles terminal escapes just fine--pass
|
||||
``force_styling=True`` to the ``Terminal`` constructor.
|
||||
|
||||
In any case, there is an ``is_a_tty`` attribute on ``Terminal`` that lets you
|
||||
see whether the attached stream seems to be a terminal. If it's false, you
|
||||
might refrain from drawing progress bars and other frippery, since you're
|
||||
apparently headed into a pipe::
|
||||
|
||||
from blessings import Terminal
|
||||
|
||||
term = Terminal()
|
||||
if term.is_a_tty:
|
||||
with term.location(0, term.height - 1):
|
||||
print 'Progress: [=======> ]'
|
||||
print term.bold('Important stuff')
|
||||
|
||||
Shopping List
|
||||
=============
|
||||
|
||||
There are decades of legacy tied up in terminal interaction, so attention to
|
||||
detail and behavior in edge cases make a difference. Here are some ways
|
||||
Blessings has your back:
|
||||
|
||||
* Uses the terminfo database so it works with any terminal type
|
||||
* Provides up-to-the-moment terminal height and width, so you can respond to
|
||||
terminal size changes (SIGWINCH signals). (Most other libraries query the
|
||||
``COLUMNS`` and ``LINES`` environment variables or the ``cols`` or ``lines``
|
||||
terminal capabilities, which don't update promptly, if at all.)
|
||||
* Avoids making a mess if the output gets piped to a non-terminal
|
||||
* Works great with standard Python string templating
|
||||
* Provides convenient access to all terminal capabilities, not just a sugared
|
||||
few
|
||||
* Outputs to any file-like object, not just stdout
|
||||
* Keeps a minimum of internal state, so you can feel free to mix and match with
|
||||
calls to curses or whatever other terminal libraries you like
|
||||
|
||||
Blessings does not provide...
|
||||
|
||||
* Native color support on the Windows command prompt. However, it should work
|
||||
when used in concert with colorama_.
|
||||
|
||||
.. _colorama: http://pypi.python.org/pypi/colorama/0.2.4
|
||||
|
||||
Bugs
|
||||
====
|
||||
|
||||
Bugs or suggestions? Visit the `issue tracker`_.
|
||||
|
||||
.. _`issue tracker`: https://github.com/erikrose/blessings/issues/new
|
||||
|
||||
License
|
||||
=======
|
||||
|
||||
Blessings is under the MIT License. See the LICENSE file.
|
||||
|
||||
Version History
|
||||
===============
|
||||
|
||||
1.3
|
||||
* Add ``number_of_colors``, which tells you how many colors the terminal
|
||||
supports.
|
||||
* Made ``color(n)`` and ``on_color(n)`` callable to wrap a string, like the
|
||||
named colors can. Also, make them both fall back to the ``setf`` and
|
||||
``setb`` capabilities (like the named colors do) if the ANSI ``setaf`` and
|
||||
``setab`` aren't available.
|
||||
* Allow ``color`` attr to act as an unparametrized string, not just a
|
||||
callable.
|
||||
* Make ``height`` and ``width`` examine any passed-in stream before falling
|
||||
back to stdout. (This rarely if ever affects actual behavior; it's mostly
|
||||
philosophical.)
|
||||
* Make caching simpler and slightly more efficient.
|
||||
* Get rid of a reference cycle between Terminals and FormattingStrings.
|
||||
* Update docs to reflect that terminal addressing (as in ``location()``) is
|
||||
0-based.
|
||||
|
||||
1.2
|
||||
* Added support for Python 3! We need 3.2.3 or greater, because the curses
|
||||
library couldn't decide whether to accept strs or bytes before that
|
||||
(http://bugs.python.org/issue10570).
|
||||
* Everything that comes out of the library is now unicode. This lets us
|
||||
support Python 3 without making a mess of the code, and Python 2 should
|
||||
continue to work unless you were testing types (and badly). Please file a
|
||||
bug if this causes trouble for you.
|
||||
* Changed to the MIT License for better world domination.
|
||||
* Added Sphinx docs.
|
||||
|
||||
1.1
|
||||
* Added nicely named attributes for colors.
|
||||
* Introduced compound formatting.
|
||||
* Added wrapper behavior for styling and colors.
|
||||
* Let you force capabilities to be non-empty, even if the output stream is
|
||||
not a terminal.
|
||||
* Added the ``is_a_tty`` attribute for telling whether the output stream is a
|
||||
terminal.
|
||||
* Sugared the remaining interesting string capabilities.
|
||||
* Let ``location()`` operate on just an x *or* y coordinate.
|
||||
|
||||
1.0
|
||||
* Extracted Blessings from nose-progressive, my `progress-bar-having,
|
||||
traceback-shortcutting, rootin', tootin' testrunner`_. It provided the
|
||||
tootin' functionality.
|
||||
|
||||
.. _`progress-bar-having, traceback-shortcutting, rootin', tootin' testrunner`: http://pypi.python.org/pypi/nose-progressive/
|
||||
|
||||
Keywords: terminal,tty,curses,ncurses,formatting,style,color,console
|
||||
Platform: UNKNOWN
|
||||
Classifier: Intended Audience :: Developers
|
||||
Classifier: Natural Language :: English
|
||||
Classifier: Development Status :: 5 - Production/Stable
|
||||
Classifier: Environment :: Console
|
||||
Classifier: Environment :: Console :: Curses
|
||||
Classifier: License :: OSI Approved :: MIT License
|
||||
Classifier: Operating System :: POSIX
|
||||
Classifier: Programming Language :: Python :: 2
|
||||
Classifier: Programming Language :: Python :: 2.5
|
||||
Classifier: Programming Language :: Python :: 2.6
|
||||
Classifier: Programming Language :: Python :: 2.7
|
||||
Classifier: Programming Language :: Python :: 3
|
||||
Classifier: Programming Language :: Python :: 3.2
|
||||
Classifier: Topic :: Software Development :: Libraries
|
||||
Classifier: Topic :: Software Development :: User Interfaces
|
||||
Classifier: Topic :: Terminals
|
|
@ -1,399 +0,0 @@
|
|||
=========
|
||||
Blessings
|
||||
=========
|
||||
|
||||
Coding with Blessings looks like this... ::
|
||||
|
||||
from blessings import Terminal
|
||||
|
||||
t = Terminal()
|
||||
|
||||
print t.bold('Hi there!')
|
||||
print t.bold_red_on_bright_green('It hurts my eyes!')
|
||||
|
||||
with t.location(0, t.height - 1):
|
||||
print 'This is at the bottom.'
|
||||
|
||||
Or, for byte-level control, you can drop down and play with raw terminal
|
||||
capabilities::
|
||||
|
||||
print '{t.bold}All your {t.red}bold and red base{t.normal}'.format(t=t)
|
||||
print t.wingo(2)
|
||||
|
||||
The Pitch
|
||||
=========
|
||||
|
||||
Blessings lifts several of curses_' limiting assumptions, and it makes your
|
||||
code pretty, too:
|
||||
|
||||
* Use styles, color, and maybe a little positioning without clearing the whole
|
||||
screen first.
|
||||
* Leave more than one screenful of scrollback in the buffer after your program
|
||||
exits, like a well-behaved command-line app should.
|
||||
* Get rid of all those noisy, C-like calls to ``tigetstr`` and ``tparm``, so
|
||||
your code doesn't get crowded out by terminal bookkeeping.
|
||||
* Act intelligently when somebody redirects your output to a file, omitting the
|
||||
terminal control codes the user doesn't want to see (optional).
|
||||
|
||||
.. _curses: http://docs.python.org/library/curses.html
|
||||
|
||||
Before And After
|
||||
----------------
|
||||
|
||||
Without Blessings, this is how you'd print some underlined text at the bottom
|
||||
of the screen::
|
||||
|
||||
from curses import tigetstr, setupterm, tparm
|
||||
from fcntl import ioctl
|
||||
from os import isatty
|
||||
import struct
|
||||
import sys
|
||||
from termios import TIOCGWINSZ
|
||||
|
||||
# If we want to tolerate having our output piped to other commands or
|
||||
# files without crashing, we need to do all this branching:
|
||||
if hasattr(sys.stdout, 'fileno') and isatty(sys.stdout.fileno()):
|
||||
setupterm()
|
||||
sc = tigetstr('sc')
|
||||
cup = tigetstr('cup')
|
||||
rc = tigetstr('rc')
|
||||
underline = tigetstr('smul')
|
||||
normal = tigetstr('sgr0')
|
||||
else:
|
||||
sc = cup = rc = underline = normal = ''
|
||||
print sc # Save cursor position.
|
||||
if cup:
|
||||
# tigetnum('lines') doesn't always update promptly, hence this:
|
||||
height = struct.unpack('hhhh', ioctl(0, TIOCGWINSZ, '\000' * 8))[0]
|
||||
print tparm(cup, height - 1, 0) # Move cursor to bottom.
|
||||
print 'This is {under}underlined{normal}!'.format(under=underline,
|
||||
normal=normal)
|
||||
print rc # Restore cursor position.
|
||||
|
||||
Phew! That was long and full of incomprehensible trash! Let's try it again,
|
||||
this time with Blessings::
|
||||
|
||||
from blessings import Terminal
|
||||
|
||||
term = Terminal()
|
||||
with term.location(0, term.height - 1):
|
||||
print 'This is', term.underline('pretty!')
|
||||
|
||||
Much better.
|
||||
|
||||
What It Provides
|
||||
================
|
||||
|
||||
Blessings provides just one top-level object: ``Terminal``. Instantiating a
|
||||
``Terminal`` figures out whether you're on a terminal at all and, if so, does
|
||||
any necessary terminal setup. After that, you can proceed to ask it all sorts
|
||||
of things about the terminal. Terminal terminal terminal.
|
||||
|
||||
Simple Formatting
|
||||
-----------------
|
||||
|
||||
Lots of handy formatting codes ("capabilities" in low-level parlance) are
|
||||
available as attributes on a ``Terminal``. For example::
|
||||
|
||||
from blessings import Terminal
|
||||
|
||||
term = Terminal()
|
||||
print 'I am ' + term.bold + 'bold' + term.normal + '!'
|
||||
|
||||
You can also use them as wrappers so you don't have to say ``normal``
|
||||
afterward::
|
||||
|
||||
print 'I am', term.bold('bold') + '!'
|
||||
|
||||
Or, if you want fine-grained control while maintaining some semblance of
|
||||
brevity, you can combine it with Python's string formatting, which makes
|
||||
attributes easy to access::
|
||||
|
||||
print 'All your {t.red}base {t.underline}are belong to us{t.normal}'.format(t=term)
|
||||
|
||||
Simple capabilities of interest include...
|
||||
|
||||
* ``bold``
|
||||
* ``reverse``
|
||||
* ``underline``
|
||||
* ``no_underline`` (which turns off underlining)
|
||||
* ``blink``
|
||||
* ``normal`` (which turns off everything, even colors)
|
||||
* ``clear_eol`` (clear to the end of the line)
|
||||
* ``clear_bol`` (clear to beginning of line)
|
||||
* ``clear_eos`` (clear to end of screen)
|
||||
|
||||
Here are a few more which are less likely to work on all terminals:
|
||||
|
||||
* ``dim``
|
||||
* ``italic`` and ``no_italic``
|
||||
* ``shadow`` and ``no_shadow``
|
||||
* ``standout`` and ``no_standout``
|
||||
* ``subscript`` and ``no_subscript``
|
||||
* ``superscript`` and ``no_superscript``
|
||||
* ``flash`` (which flashes the screen once)
|
||||
|
||||
Note that, while the inverse of ``underline`` is ``no_underline``, the only way
|
||||
to turn off ``bold`` or ``reverse`` is ``normal``, which also cancels any
|
||||
custom colors. This is because there's no way to tell the terminal to undo
|
||||
certain pieces of formatting, even at the lowest level.
|
||||
|
||||
You might notice that the above aren't the typical incomprehensible terminfo
|
||||
capability names; we alias a few of the harder-to-remember ones for
|
||||
readability. However, you aren't limited to these: you can reference any
|
||||
string-returning capability listed on the `terminfo man page`_ by the name
|
||||
under the "Cap-name" column: for example, ``term.rum``.
|
||||
|
||||
.. _`terminfo man page`: http://www.manpagez.com/man/5/terminfo/
|
||||
|
||||
Color
|
||||
-----
|
||||
|
||||
16 colors, both foreground and background, are available as easy-to-remember
|
||||
attributes::
|
||||
|
||||
from blessings import Terminal
|
||||
|
||||
term = Terminal()
|
||||
print term.red + term.on_green + 'Red on green? Ick!' + term.normal
|
||||
print term.bright_red + term.on_bright_blue + 'This is even worse!' + term.normal
|
||||
|
||||
You can also call them as wrappers, which sets everything back to normal at the
|
||||
end::
|
||||
|
||||
print term.red_on_green('Red on green? Ick!')
|
||||
print term.yellow('I can barely see it.')
|
||||
|
||||
The available colors are...
|
||||
|
||||
* ``black``
|
||||
* ``red``
|
||||
* ``green``
|
||||
* ``yellow``
|
||||
* ``blue``
|
||||
* ``magenta``
|
||||
* ``cyan``
|
||||
* ``white``
|
||||
|
||||
You can set the background color instead of the foreground by prepending
|
||||
``on_``, as in ``on_blue``. There is also a ``bright`` version of each color:
|
||||
for example, ``on_bright_blue``.
|
||||
|
||||
There is also a numerical interface to colors, which takes an integer from
|
||||
0-15::
|
||||
|
||||
term.color(5) + 'Hello' + term.normal
|
||||
term.on_color(3) + 'Hello' + term.normal
|
||||
|
||||
term.color(5)('Hello')
|
||||
term.on_color(3)('Hello')
|
||||
|
||||
If some color is unsupported (for instance, if only the normal colors are
|
||||
available, not the bright ones), trying to use it will, on most terminals, have
|
||||
no effect: the foreground and background colors will stay as they were. You can
|
||||
get fancy and do different things depending on the supported colors by checking
|
||||
`number_of_colors`_.
|
||||
|
||||
.. _`number_of_colors`: http://packages.python.org/blessings/#blessings.Terminal.number_of_colors
|
||||
|
||||
Compound Formatting
|
||||
-------------------
|
||||
|
||||
If you want to do lots of crazy formatting all at once, you can just mash it
|
||||
all together::
|
||||
|
||||
from blessings import Terminal
|
||||
|
||||
term = Terminal()
|
||||
print term.bold_underline_green_on_yellow + 'Woo' + term.normal
|
||||
|
||||
Or you can use your newly coined attribute as a wrapper, which implicitly sets
|
||||
everything back to normal afterward::
|
||||
|
||||
print term.bold_underline_green_on_yellow('Woo')
|
||||
|
||||
This compound notation comes in handy if you want to allow users to customize
|
||||
the formatting of your app: just have them pass in a format specifier like
|
||||
"bold_green" on the command line, and do a quick ``getattr(term,
|
||||
that_option)('Your text')`` when you do your formatting.
|
||||
|
||||
I'd be remiss if I didn't credit couleur_, where I probably got the idea for
|
||||
all this mashing.
|
||||
|
||||
.. _couleur: http://pypi.python.org/pypi/couleur
|
||||
|
||||
Parametrized Capabilities
|
||||
-------------------------
|
||||
|
||||
Some capabilities take parameters. Rather than making you dig up ``tparm()``
|
||||
all the time, we simply make such capabilities into callable strings. You can
|
||||
pass the parameters right in::
|
||||
|
||||
from blessings import Terminal
|
||||
|
||||
term = Terminal()
|
||||
print term.move(10, 1)
|
||||
|
||||
Here are some of interest:
|
||||
|
||||
``move``
|
||||
Position the cursor elsewhere. Parameters are y coordinate, then x
|
||||
coordinate.
|
||||
``move_x``
|
||||
Move the cursor to the given column.
|
||||
``move_y``
|
||||
Move the cursor to the given row.
|
||||
|
||||
You can also reference any other string-returning capability listed on the
|
||||
`terminfo man page`_ by its name under the "Cap-name" column.
|
||||
|
||||
.. _`terminfo man page`: http://www.manpagez.com/man/5/terminfo/
|
||||
|
||||
Height and Width
|
||||
----------------
|
||||
|
||||
It's simple to get the height and width of the terminal, in characters::
|
||||
|
||||
from blessings import Terminal
|
||||
|
||||
term = Terminal()
|
||||
height = term.height
|
||||
width = term.width
|
||||
|
||||
These are newly updated each time you ask for them, so they're safe to use from
|
||||
SIGWINCH handlers.
|
||||
|
||||
Temporary Repositioning
|
||||
-----------------------
|
||||
|
||||
Sometimes you need to flit to a certain location, print something, and then
|
||||
return: for example, when updating a progress bar at the bottom of the screen.
|
||||
``Terminal`` provides a context manager for doing this concisely::
|
||||
|
||||
from blessings import Terminal
|
||||
|
||||
term = Terminal()
|
||||
with term.location(0, term.height - 1):
|
||||
print 'Here is the bottom.'
|
||||
print 'This is back where I came from.'
|
||||
|
||||
Parameters to ``location()`` are ``x`` and then ``y``, but you can also pass
|
||||
just one of them, leaving the other alone. For example... ::
|
||||
|
||||
with term.location(y=10):
|
||||
print 'We changed just the row.'
|
||||
|
||||
If you want to reposition permanently, see ``move``, in an example above.
|
||||
|
||||
Pipe Savvy
|
||||
----------
|
||||
|
||||
If your program isn't attached to a terminal, like if it's being piped to
|
||||
another command or redirected to a file, all the capability attributes on
|
||||
``Terminal`` will return empty strings. You'll get a nice-looking file without
|
||||
any formatting codes gumming up the works.
|
||||
|
||||
If you want to override this--like if you anticipate your program being piped
|
||||
through ``less -r``, which handles terminal escapes just fine--pass
|
||||
``force_styling=True`` to the ``Terminal`` constructor.
|
||||
|
||||
In any case, there is an ``is_a_tty`` attribute on ``Terminal`` that lets you
|
||||
see whether the attached stream seems to be a terminal. If it's false, you
|
||||
might refrain from drawing progress bars and other frippery, since you're
|
||||
apparently headed into a pipe::
|
||||
|
||||
from blessings import Terminal
|
||||
|
||||
term = Terminal()
|
||||
if term.is_a_tty:
|
||||
with term.location(0, term.height - 1):
|
||||
print 'Progress: [=======> ]'
|
||||
print term.bold('Important stuff')
|
||||
|
||||
Shopping List
|
||||
=============
|
||||
|
||||
There are decades of legacy tied up in terminal interaction, so attention to
|
||||
detail and behavior in edge cases make a difference. Here are some ways
|
||||
Blessings has your back:
|
||||
|
||||
* Uses the terminfo database so it works with any terminal type
|
||||
* Provides up-to-the-moment terminal height and width, so you can respond to
|
||||
terminal size changes (SIGWINCH signals). (Most other libraries query the
|
||||
``COLUMNS`` and ``LINES`` environment variables or the ``cols`` or ``lines``
|
||||
terminal capabilities, which don't update promptly, if at all.)
|
||||
* Avoids making a mess if the output gets piped to a non-terminal
|
||||
* Works great with standard Python string templating
|
||||
* Provides convenient access to all terminal capabilities, not just a sugared
|
||||
few
|
||||
* Outputs to any file-like object, not just stdout
|
||||
* Keeps a minimum of internal state, so you can feel free to mix and match with
|
||||
calls to curses or whatever other terminal libraries you like
|
||||
|
||||
Blessings does not provide...
|
||||
|
||||
* Native color support on the Windows command prompt. However, it should work
|
||||
when used in concert with colorama_.
|
||||
|
||||
.. _colorama: http://pypi.python.org/pypi/colorama/0.2.4
|
||||
|
||||
Bugs
|
||||
====
|
||||
|
||||
Bugs or suggestions? Visit the `issue tracker`_.
|
||||
|
||||
.. _`issue tracker`: https://github.com/erikrose/blessings/issues/new
|
||||
|
||||
License
|
||||
=======
|
||||
|
||||
Blessings is under the MIT License. See the LICENSE file.
|
||||
|
||||
Version History
|
||||
===============
|
||||
|
||||
1.3
|
||||
* Add ``number_of_colors``, which tells you how many colors the terminal
|
||||
supports.
|
||||
* Made ``color(n)`` and ``on_color(n)`` callable to wrap a string, like the
|
||||
named colors can. Also, make them both fall back to the ``setf`` and
|
||||
``setb`` capabilities (like the named colors do) if the ANSI ``setaf`` and
|
||||
``setab`` aren't available.
|
||||
* Allow ``color`` attr to act as an unparametrized string, not just a
|
||||
callable.
|
||||
* Make ``height`` and ``width`` examine any passed-in stream before falling
|
||||
back to stdout. (This rarely if ever affects actual behavior; it's mostly
|
||||
philosophical.)
|
||||
* Make caching simpler and slightly more efficient.
|
||||
* Get rid of a reference cycle between Terminals and FormattingStrings.
|
||||
* Update docs to reflect that terminal addressing (as in ``location()``) is
|
||||
0-based.
|
||||
|
||||
1.2
|
||||
* Added support for Python 3! We need 3.2.3 or greater, because the curses
|
||||
library couldn't decide whether to accept strs or bytes before that
|
||||
(http://bugs.python.org/issue10570).
|
||||
* Everything that comes out of the library is now unicode. This lets us
|
||||
support Python 3 without making a mess of the code, and Python 2 should
|
||||
continue to work unless you were testing types (and badly). Please file a
|
||||
bug if this causes trouble for you.
|
||||
* Changed to the MIT License for better world domination.
|
||||
* Added Sphinx docs.
|
||||
|
||||
1.1
|
||||
* Added nicely named attributes for colors.
|
||||
* Introduced compound formatting.
|
||||
* Added wrapper behavior for styling and colors.
|
||||
* Let you force capabilities to be non-empty, even if the output stream is
|
||||
not a terminal.
|
||||
* Added the ``is_a_tty`` attribute for telling whether the output stream is a
|
||||
terminal.
|
||||
* Sugared the remaining interesting string capabilities.
|
||||
* Let ``location()`` operate on just an x *or* y coordinate.
|
||||
|
||||
1.0
|
||||
* Extracted Blessings from nose-progressive, my `progress-bar-having,
|
||||
traceback-shortcutting, rootin', tootin' testrunner`_. It provided the
|
||||
tootin' functionality.
|
||||
|
||||
.. _`progress-bar-having, traceback-shortcutting, rootin', tootin' testrunner`: http://pypi.python.org/pypi/nose-progressive/
|
|
@ -1,14 +1,18 @@
|
|||
from collections import defaultdict
|
||||
"""A thin, practical wrapper around terminal coloring, styling, and
|
||||
positioning"""
|
||||
|
||||
from contextlib import contextmanager
|
||||
import curses
|
||||
from curses import tigetstr, tigetnum, setupterm, tparm
|
||||
from curses import setupterm, tigetnum, tigetstr, tparm
|
||||
from fcntl import ioctl
|
||||
|
||||
try:
|
||||
from io import UnsupportedOperation as IOUnsupportedOperation
|
||||
except ImportError:
|
||||
class IOUnsupportedOperation(Exception):
|
||||
"""A dummy exception to take the place of Python 3's ``io.UnsupportedOperation`` in Python 2"""
|
||||
pass
|
||||
import os
|
||||
"""A dummy exception to take the place of Python 3's
|
||||
``io.UnsupportedOperation`` in Python 2"""
|
||||
|
||||
from os import isatty, environ
|
||||
from platform import python_version_tuple
|
||||
import struct
|
||||
|
@ -16,15 +20,16 @@ import sys
|
|||
from termios import TIOCGWINSZ
|
||||
|
||||
|
||||
if ('3', '0', '0') <= python_version_tuple() < ('3', '2', '2+'): # Good till 3.2.10
|
||||
__all__ = ['Terminal']
|
||||
|
||||
|
||||
if ('3', '0', '0') <= python_version_tuple() < ('3', '2', '2+'): # Good till
|
||||
# 3.2.10
|
||||
# Python 3.x < 3.2.3 has a bug in which tparm() erroneously takes a string.
|
||||
raise ImportError('Blessings needs Python 3.2.3 or greater for Python 3 '
|
||||
'support due to http://bugs.python.org/issue10570.')
|
||||
|
||||
|
||||
__all__ = ['Terminal']
|
||||
|
||||
|
||||
class Terminal(object):
|
||||
"""An abstraction around terminal capabilities
|
||||
|
||||
|
@ -40,9 +45,6 @@ class Terminal(object):
|
|||
around with the terminal; it's almost always needed when the terminal
|
||||
is and saves sticking lots of extra args on client functions in
|
||||
practice.
|
||||
``is_a_tty``
|
||||
Whether ``stream`` appears to be a terminal. You can examine this value
|
||||
to decide whether to draw progress bars or other frippery.
|
||||
|
||||
"""
|
||||
def __init__(self, kind=None, stream=None, force_styling=False):
|
||||
|
@ -69,26 +71,31 @@ class Terminal(object):
|
|||
somewhere, and stdout is probably where the output is ultimately
|
||||
headed. If not, stderr is probably bound to the same terminal.)
|
||||
|
||||
If you want to force styling to not happen, pass
|
||||
``force_styling=None``.
|
||||
|
||||
"""
|
||||
if stream is None:
|
||||
stream = sys.__stdout__
|
||||
try:
|
||||
stream_descriptor = (stream.fileno() if hasattr(stream, 'fileno')
|
||||
and callable(stream.fileno)
|
||||
and callable(stream.fileno)
|
||||
else None)
|
||||
except IOUnsupportedOperation:
|
||||
stream_descriptor = None
|
||||
|
||||
self.is_a_tty = stream_descriptor is not None and isatty(stream_descriptor)
|
||||
self._does_styling = self.is_a_tty or force_styling
|
||||
self._is_a_tty = (stream_descriptor is not None and
|
||||
isatty(stream_descriptor))
|
||||
self._does_styling = ((self.is_a_tty or force_styling) and
|
||||
force_styling is not None)
|
||||
|
||||
# The desciptor to direct terminal initialization sequences to.
|
||||
# The descriptor to direct terminal initialization sequences to.
|
||||
# sys.__stdout__ seems to always have a descriptor of 1, even if output
|
||||
# is redirected.
|
||||
self._init_descriptor = (sys.__stdout__.fileno()
|
||||
if stream_descriptor is None
|
||||
else stream_descriptor)
|
||||
if self._does_styling:
|
||||
if self.does_styling:
|
||||
# Make things like tigetstr() work. Explicit args make setupterm()
|
||||
# work even when -s is passed to nosetests. Lean toward sending
|
||||
# init sequences to the stream if it has a file descriptor, and
|
||||
|
@ -111,10 +118,20 @@ class Terminal(object):
|
|||
clear_eol='el',
|
||||
clear_bol='el1',
|
||||
clear_eos='ed',
|
||||
# 'clear' clears the whole screen.
|
||||
position='cup', # deprecated
|
||||
enter_fullscreen='smcup',
|
||||
exit_fullscreen='rmcup',
|
||||
move='cup',
|
||||
move_x='hpa',
|
||||
move_y='vpa',
|
||||
move_left='cub1',
|
||||
move_right='cuf1',
|
||||
move_up='cuu1',
|
||||
move_down='cud1',
|
||||
|
||||
hide_cursor='civis',
|
||||
normal_cursor='cnorm',
|
||||
|
||||
reset_colors='op', # oc doesn't work on my OS X terminal.
|
||||
|
||||
|
@ -138,7 +155,7 @@ class Terminal(object):
|
|||
no_underline='rmul')
|
||||
|
||||
def __getattr__(self, attr):
|
||||
"""Return parametrized terminal capabilities, like bold.
|
||||
"""Return a terminal capability, like bold.
|
||||
|
||||
For example, you can say ``term.bold`` to get the string that turns on
|
||||
bold formatting and ``term.normal`` to get the string that turns it off
|
||||
|
@ -154,10 +171,27 @@ class Terminal(object):
|
|||
Return values are always Unicode.
|
||||
|
||||
"""
|
||||
resolution = self._resolve_formatter(attr) if self._does_styling else NullCallableString()
|
||||
resolution = (self._resolve_formatter(attr) if self.does_styling
|
||||
else NullCallableString())
|
||||
setattr(self, attr, resolution) # Cache capability codes.
|
||||
return resolution
|
||||
|
||||
@property
|
||||
def does_styling(self):
|
||||
"""Whether attempt to emit capabilities
|
||||
|
||||
This is influenced by the ``is_a_tty`` property and by the
|
||||
``force_styling`` argument to the constructor. You can examine
|
||||
this value to decide whether to draw progress bars or other frippery.
|
||||
|
||||
"""
|
||||
return self._does_styling
|
||||
|
||||
@property
|
||||
def is_a_tty(self):
|
||||
"""Whether my ``stream`` appears to be associated with a terminal"""
|
||||
return self._is_a_tty
|
||||
|
||||
@property
|
||||
def height(self):
|
||||
"""The height of the terminal in characters
|
||||
|
@ -167,8 +201,8 @@ class Terminal(object):
|
|||
piping to things that eventually display on the terminal (like ``less
|
||||
-R``) work. If a stream representing a terminal was passed in, return
|
||||
the dimensions of that terminal. If there somehow is no controlling
|
||||
terminal, return ``None``. (Thus, you should check that ``is_a_tty`` is
|
||||
true before doing any math on the result.)
|
||||
terminal, return ``None``. (Thus, you should check that the property
|
||||
``is_a_tty`` is true before doing any math on the result.)
|
||||
|
||||
"""
|
||||
return self._height_and_width()[0]
|
||||
|
@ -183,16 +217,30 @@ class Terminal(object):
|
|||
return self._height_and_width()[1]
|
||||
|
||||
def _height_and_width(self):
|
||||
"""Return a tuple of (terminal height, terminal width)."""
|
||||
"""Return a tuple of (terminal height, terminal width).
|
||||
|
||||
Start by trying TIOCGWINSZ (Terminal I/O-Control: Get Window Size),
|
||||
falling back to environment variables (LINES, COLUMNS), and returning
|
||||
(None, None) if those are unavailable or invalid.
|
||||
|
||||
"""
|
||||
# tigetnum('lines') and tigetnum('cols') update only if we call
|
||||
# setupterm() again.
|
||||
for descriptor in self._init_descriptor, sys.__stdout__:
|
||||
try:
|
||||
return struct.unpack('hhhh', ioctl(descriptor, TIOCGWINSZ, '\000' * 8))[0:2]
|
||||
return struct.unpack(
|
||||
'hhhh', ioctl(descriptor, TIOCGWINSZ, '\000' * 8))[0:2]
|
||||
except IOError:
|
||||
# when the output stream or init descriptor is not a tty, such
|
||||
# as when when stdout is piped to another program, fe. tee(1),
|
||||
# these ioctls will raise IOError
|
||||
pass
|
||||
return None, None # Should never get here
|
||||
try:
|
||||
return int(environ.get('LINES')), int(environ.get('COLUMNS'))
|
||||
except TypeError:
|
||||
return None, None
|
||||
|
||||
@contextmanager
|
||||
def location(self, x=None, y=None):
|
||||
"""Return a context manager for temporarily moving the cursor.
|
||||
|
||||
|
@ -206,10 +254,45 @@ class Terminal(object):
|
|||
print 'I can do it %i times!' % x
|
||||
|
||||
Specify ``x`` to move to a certain column, ``y`` to move to a certain
|
||||
row, or both.
|
||||
row, both, or neither. If you specify neither, only the saving and
|
||||
restoration of cursor position will happen. This can be useful if you
|
||||
simply want to restore your place after doing some manual cursor
|
||||
movement.
|
||||
|
||||
"""
|
||||
return Location(self, x, y)
|
||||
# Save position and move to the requested column, row, or both:
|
||||
self.stream.write(self.save)
|
||||
if x is not None and y is not None:
|
||||
self.stream.write(self.move(y, x))
|
||||
elif x is not None:
|
||||
self.stream.write(self.move_x(x))
|
||||
elif y is not None:
|
||||
self.stream.write(self.move_y(y))
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
# Restore original cursor position:
|
||||
self.stream.write(self.restore)
|
||||
|
||||
@contextmanager
|
||||
def fullscreen(self):
|
||||
"""Return a context manager that enters fullscreen mode while inside it
|
||||
and restores normal mode on leaving."""
|
||||
self.stream.write(self.enter_fullscreen)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
self.stream.write(self.exit_fullscreen)
|
||||
|
||||
@contextmanager
|
||||
def hidden_cursor(self):
|
||||
"""Return a context manager that hides the cursor while inside it and
|
||||
makes it visible on leaving."""
|
||||
self.stream.write(self.hide_cursor)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
self.stream.write(self.normal_cursor)
|
||||
|
||||
@property
|
||||
def color(self):
|
||||
|
@ -254,12 +337,22 @@ class Terminal(object):
|
|||
# don't name it after the underlying capability, because we deviate
|
||||
# slightly from its behavior, and we might someday wish to give direct
|
||||
# access to it.
|
||||
colors = tigetnum('colors') # Returns -1 if no color support, -2 if no such cap.
|
||||
#self.__dict__['colors'] = ret # Cache it. It's not changing. (Doesn't work.)
|
||||
if not self._does_styling:
|
||||
return 0
|
||||
|
||||
colors = tigetnum('colors') # Returns -1 if no color support, -2 if no
|
||||
# such cap.
|
||||
# self.__dict__['colors'] = ret # Cache it. It's not changing.
|
||||
# (Doesn't work.)
|
||||
return colors if colors >= 0 else 0
|
||||
|
||||
def _resolve_formatter(self, attr):
|
||||
"""Resolve a sugary or plain capability name, color, or compound formatting function name into a callable capability."""
|
||||
"""Resolve a sugary or plain capability name, color, or compound
|
||||
formatting function name into a callable capability.
|
||||
|
||||
Return a ``ParametrizingString`` or a ``FormattingString``.
|
||||
|
||||
"""
|
||||
if attr in COLORS:
|
||||
return self._resolve_color(attr)
|
||||
elif attr in COMPOUNDABLES:
|
||||
|
@ -277,7 +370,8 @@ class Terminal(object):
|
|||
return ParametrizingString(self._resolve_capability(attr))
|
||||
|
||||
def _resolve_capability(self, atom):
|
||||
"""Return a terminal code for a capname or a sugary name, or an empty Unicode.
|
||||
"""Return a terminal code for a capname or a sugary name, or an empty
|
||||
Unicode.
|
||||
|
||||
The return value is always Unicode, because otherwise it is clumsy
|
||||
(especially in Python 3) to concatenate with real (Unicode) strings.
|
||||
|
@ -285,14 +379,13 @@ class Terminal(object):
|
|||
"""
|
||||
code = tigetstr(self._sugar.get(atom, atom))
|
||||
if code:
|
||||
# We can encode escape sequences as UTF-8 because they never
|
||||
# contain chars > 127, and UTF-8 never changes anything within that
|
||||
# range..
|
||||
return code.decode('utf-8')
|
||||
# See the comment in ParametrizingString for why this is latin1.
|
||||
return code.decode('latin1')
|
||||
return u''
|
||||
|
||||
def _resolve_color(self, color):
|
||||
"""Resolve a color like red or on_bright_green into a callable capability."""
|
||||
"""Resolve a color like red or on_bright_green into a callable
|
||||
capability."""
|
||||
# TODO: Does curses automatically exchange red and blue and cyan and
|
||||
# yellow when a terminal supports setf/setb rather than setaf/setab?
|
||||
# I'll be blasted if I can find any documentation. The following
|
||||
|
@ -315,7 +408,8 @@ class Terminal(object):
|
|||
return self.setab or self.setb
|
||||
|
||||
def _formatting_string(self, formatting):
|
||||
"""Return a new ``FormattingString`` which implicitly receives my notion of "normal"."""
|
||||
"""Return a new ``FormattingString`` which implicitly receives my
|
||||
notion of "normal"."""
|
||||
return FormattingString(formatting, self.normal)
|
||||
|
||||
|
||||
|
@ -326,7 +420,8 @@ def derivative_colors(colors):
|
|||
[('on_bright_' + c) for c in colors])
|
||||
|
||||
|
||||
COLORS = set(['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'])
|
||||
COLORS = set(['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan',
|
||||
'white'])
|
||||
COLORS.update(derivative_colors(COLORS))
|
||||
COMPOUNDABLES = (COLORS |
|
||||
set(['bold', 'underline', 'reverse', 'blink', 'dim', 'italic',
|
||||
|
@ -334,7 +429,9 @@ COMPOUNDABLES = (COLORS |
|
|||
|
||||
|
||||
class ParametrizingString(unicode):
|
||||
"""A Unicode string which can be called to parametrize it as a terminal capability"""
|
||||
"""A Unicode string which can be called to parametrize it as a terminal
|
||||
capability"""
|
||||
|
||||
def __new__(cls, formatting, normal=None):
|
||||
"""Instantiate.
|
||||
|
||||
|
@ -352,7 +449,15 @@ class ParametrizingString(unicode):
|
|||
# Re-encode the cap, because tparm() takes a bytestring in Python
|
||||
# 3. However, appear to be a plain Unicode string otherwise so
|
||||
# concats work.
|
||||
parametrized = tparm(self.encode('utf-8'), *args).decode('utf-8')
|
||||
#
|
||||
# We use *latin1* encoding so that bytes emitted by tparm are
|
||||
# encoded to their native value: some terminal kinds, such as
|
||||
# 'avatar' or 'kermit', emit 8-bit bytes in range 0x7f to 0xff.
|
||||
# latin1 leaves these values unmodified in their conversion to
|
||||
# unicode byte values. The terminal emulator will "catch" and
|
||||
# handle these values, even if emitting utf8-encoded text, where
|
||||
# these bytes would otherwise be illegal utf8 start bytes.
|
||||
parametrized = tparm(self.encode('latin1'), *args).decode('latin1')
|
||||
return (parametrized if self._normal is None else
|
||||
FormattingString(parametrized, self._normal))
|
||||
except curses.error:
|
||||
|
@ -376,7 +481,9 @@ class ParametrizingString(unicode):
|
|||
|
||||
|
||||
class FormattingString(unicode):
|
||||
"""A Unicode string which can be called upon a piece of text to wrap it in formatting"""
|
||||
"""A Unicode string which can be called upon a piece of text to wrap it in
|
||||
formatting"""
|
||||
|
||||
def __new__(cls, formatting, normal):
|
||||
new = unicode.__new__(cls, formatting)
|
||||
new._normal = normal
|
||||
|
@ -394,21 +501,48 @@ class FormattingString(unicode):
|
|||
|
||||
|
||||
class NullCallableString(unicode):
|
||||
"""A dummy class to stand in for ``FormattingString`` and ``ParametrizingString``
|
||||
"""A dummy callable Unicode to stand in for ``FormattingString`` and
|
||||
``ParametrizingString``
|
||||
|
||||
A callable bytestring that returns an empty Unicode when called with an int
|
||||
and the arg otherwise. We use this when there is no tty and so all
|
||||
capabilities are blank.
|
||||
We use this when there is no tty and thus all capabilities should be blank.
|
||||
|
||||
"""
|
||||
def __new__(cls):
|
||||
new = unicode.__new__(cls, u'')
|
||||
return new
|
||||
|
||||
def __call__(self, arg):
|
||||
if isinstance(arg, int):
|
||||
def __call__(self, *args):
|
||||
"""Return a Unicode or whatever you passed in as the first arg
|
||||
(hopefully a string of some kind).
|
||||
|
||||
When called with an int as the first arg, return an empty Unicode. An
|
||||
int is a good hint that I am a ``ParametrizingString``, as there are
|
||||
only about half a dozen string-returning capabilities on OS X's
|
||||
terminfo man page which take any param that's not an int, and those are
|
||||
seldom if ever used on modern terminal emulators. (Most have to do with
|
||||
programming function keys. Blessings' story for supporting
|
||||
non-string-returning caps is undeveloped.) And any parametrized
|
||||
capability in a situation where all capabilities themselves are taken
|
||||
to be blank are, of course, themselves blank.
|
||||
|
||||
When called with a non-int as the first arg (no no args at all), return
|
||||
the first arg. I am acting as a ``FormattingString``.
|
||||
|
||||
"""
|
||||
if len(args) != 1 or isinstance(args[0], int):
|
||||
# I am acting as a ParametrizingString.
|
||||
|
||||
# tparm can take not only ints but also (at least) strings as its
|
||||
# second...nth args. But we don't support callably parametrizing
|
||||
# caps that take non-ints yet, so we can cheap out here. TODO: Go
|
||||
# through enough of the motions in the capability resolvers to
|
||||
# determine which of 2 special-purpose classes,
|
||||
# NullParametrizableString or NullFormattingString, to return, and
|
||||
# retire this one.
|
||||
return u''
|
||||
return arg # TODO: Force even strs in Python 2.x to be unicodes? Nah. How would I know what encoding to use to convert it?
|
||||
return args[0] # Should we force even strs in Python 2.x to be
|
||||
# unicodes? No. How would I know what encoding to use
|
||||
# to convert it?
|
||||
|
||||
|
||||
def split_into_formatters(compound):
|
||||
|
@ -427,24 +561,3 @@ def split_into_formatters(compound):
|
|||
else:
|
||||
merged_segs.append(s)
|
||||
return merged_segs
|
||||
|
||||
|
||||
class Location(object):
|
||||
"""Context manager for temporarily moving the cursor"""
|
||||
def __init__(self, term, x=None, y=None):
|
||||
self.x, self.y = x, y
|
||||
self.term = term
|
||||
|
||||
def __enter__(self):
|
||||
"""Save position and move to the requested column, row, or both."""
|
||||
self.term.stream.write(self.term.save) # save position
|
||||
if self.x and self.y:
|
||||
self.term.stream.write(self.term.move(self.y, self.x))
|
||||
elif self.x:
|
||||
self.term.stream.write(self.term.move_x(self.x))
|
||||
elif self.y:
|
||||
self.term.stream.write(self.term.move_y(self.y))
|
||||
|
||||
def __exit__(self, type, value, tb):
|
||||
"""Restore original cursor position."""
|
||||
self.term.stream.write(self.term.restore)
|
||||
|
|
|
@ -28,12 +28,12 @@ TestTerminal = partial(Terminal, kind='xterm-256color')
|
|||
|
||||
def unicode_cap(cap):
|
||||
"""Return the result of ``tigetstr`` except as Unicode."""
|
||||
return tigetstr(cap).decode('utf-8')
|
||||
return tigetstr(cap).decode('latin1')
|
||||
|
||||
|
||||
def unicode_parm(cap, *parms):
|
||||
"""Return the result of ``tparm(tigetstr())`` except as Unicode."""
|
||||
return tparm(tigetstr(cap), *parms).decode('utf-8')
|
||||
return tparm(tigetstr(cap), *parms).decode('latin1')
|
||||
|
||||
|
||||
def test_capability():
|
||||
|
@ -57,7 +57,8 @@ def test_capability_without_tty():
|
|||
|
||||
|
||||
def test_capability_with_forced_tty():
|
||||
"""If we force styling, capabilities had better not (generally) be empty."""
|
||||
"""If we force styling, capabilities had better not (generally) be
|
||||
empty."""
|
||||
t = TestTerminal(stream=StringIO(), force_styling=True)
|
||||
eq_(t.save, unicode_cap('sc'))
|
||||
|
||||
|
@ -67,15 +68,16 @@ def test_parametrization():
|
|||
eq_(TestTerminal().cup(3, 4), unicode_parm('cup', 3, 4))
|
||||
|
||||
|
||||
def height_and_width():
|
||||
def test_height_and_width():
|
||||
"""Assert that ``height_and_width()`` returns ints."""
|
||||
t = TestTerminal() # kind shouldn't matter.
|
||||
assert isinstance(int, t.height)
|
||||
assert isinstance(int, t.width)
|
||||
assert isinstance(t.height, int)
|
||||
assert isinstance(t.width, int)
|
||||
|
||||
|
||||
def test_stream_attr():
|
||||
"""Make sure Terminal exposes a ``stream`` attribute that defaults to something sane."""
|
||||
"""Make sure Terminal exposes a ``stream`` attribute that defaults to
|
||||
something sane."""
|
||||
eq_(Terminal().stream, sys.__stdout__)
|
||||
|
||||
|
||||
|
@ -102,6 +104,25 @@ def test_horizontal_location():
|
|||
unicode_cap('rc'))
|
||||
|
||||
|
||||
def test_null_location():
|
||||
"""Make sure ``location()`` with no args just does position restoration."""
|
||||
t = TestTerminal(stream=StringIO(), force_styling=True)
|
||||
with t.location():
|
||||
pass
|
||||
eq_(t.stream.getvalue(), unicode_cap('sc') +
|
||||
unicode_cap('rc'))
|
||||
|
||||
|
||||
def test_zero_location():
|
||||
"""Make sure ``location()`` pays attention to 0-valued args."""
|
||||
t = TestTerminal(stream=StringIO(), force_styling=True)
|
||||
with t.location(0, 0):
|
||||
pass
|
||||
eq_(t.stream.getvalue(), unicode_cap('sc') +
|
||||
unicode_parm('cup', 0, 0) +
|
||||
unicode_cap('rc'))
|
||||
|
||||
|
||||
def test_null_fileno():
|
||||
"""Make sure ``Terminal`` works when ``fileno`` is ``None``.
|
||||
|
||||
|
@ -178,7 +199,8 @@ def test_number_of_colors_with_tty():
|
|||
def test_formatting_functions():
|
||||
"""Test crazy-ass formatting wrappers, both simple and compound."""
|
||||
t = TestTerminal()
|
||||
# By now, it should be safe to use sugared attributes. Other tests test those.
|
||||
# By now, it should be safe to use sugared attributes. Other tests test
|
||||
# those.
|
||||
eq_(t.bold(u'hi'), t.bold + u'hi' + t.normal)
|
||||
eq_(t.green('hi'), t.green + u'hi' + t.normal) # Plain strs for Python 2.x
|
||||
# Test some non-ASCII chars, probably not necessary:
|
||||
|
@ -187,7 +209,8 @@ def test_formatting_functions():
|
|||
t.bold + t.underline + t.green + t.on_red + u'boo' + t.normal)
|
||||
# Don't spell things like this:
|
||||
eq_(t.on_bright_red_bold_bright_green_underline('meh'),
|
||||
t.on_bright_red + t.bold + t.bright_green + t.underline + u'meh' + t.normal)
|
||||
t.on_bright_red + t.bold + t.bright_green + t.underline + u'meh' +
|
||||
t.normal)
|
||||
|
||||
|
||||
def test_formatting_functions_without_tty():
|
||||
|
@ -229,3 +252,19 @@ def test_init_descriptor_always_initted():
|
|||
"""We should be able to get a height and width even on no-tty Terminals."""
|
||||
t = Terminal(stream=StringIO())
|
||||
eq_(type(t.height), int)
|
||||
|
||||
|
||||
def test_force_styling_none():
|
||||
"""If ``force_styling=None`` is passed to the constructor, don't ever do
|
||||
styling."""
|
||||
t = TestTerminal(force_styling=None)
|
||||
eq_(t.save, '')
|
||||
|
||||
|
||||
def test_null_callable_string():
|
||||
"""Make sure NullCallableString tolerates all numbers and kinds of args it
|
||||
might receive."""
|
||||
t = TestTerminal(stream=StringIO())
|
||||
eq_(t.clear, '')
|
||||
eq_(t.move(1, 2), '')
|
||||
eq_(t.move_x(1), '')
|
||||
|
|
|
@ -1,5 +0,0 @@
|
|||
[egg_info]
|
||||
tag_build =
|
||||
tag_date = 0
|
||||
tag_svn_revision = 0
|
||||
|
|
@ -1,42 +0,0 @@
|
|||
import sys
|
||||
|
||||
from setuptools import setup, find_packages
|
||||
|
||||
|
||||
extra_setup = {}
|
||||
if sys.version_info >= (3,):
|
||||
extra_setup['use_2to3'] = True
|
||||
|
||||
setup(
|
||||
name='blessings',
|
||||
version='1.3',
|
||||
description='A thin, practical wrapper around terminal formatting, positioning, and more',
|
||||
long_description=open('README.rst').read(),
|
||||
author='Erik Rose',
|
||||
author_email='erikrose@grinchcentral.com',
|
||||
license='MIT',
|
||||
packages=find_packages(exclude=['ez_setup']),
|
||||
tests_require=['Nose'],
|
||||
url='https://github.com/erikrose/blessings',
|
||||
include_package_data=True,
|
||||
classifiers=[
|
||||
'Intended Audience :: Developers',
|
||||
'Natural Language :: English',
|
||||
'Development Status :: 5 - Production/Stable',
|
||||
'Environment :: Console',
|
||||
'Environment :: Console :: Curses',
|
||||
'License :: OSI Approved :: MIT License',
|
||||
'Operating System :: POSIX',
|
||||
'Programming Language :: Python :: 2',
|
||||
'Programming Language :: Python :: 2.5',
|
||||
'Programming Language :: Python :: 2.6',
|
||||
'Programming Language :: Python :: 2.7',
|
||||
'Programming Language :: Python :: 3',
|
||||
'Programming Language :: Python :: 3.2',
|
||||
'Topic :: Software Development :: Libraries',
|
||||
'Topic :: Software Development :: User Interfaces',
|
||||
'Topic :: Terminals'
|
||||
],
|
||||
keywords=['terminal', 'tty', 'curses', 'ncurses', 'formatting', 'style', 'color', 'console'],
|
||||
**extra_setup
|
||||
)
|
|
@ -1,7 +0,0 @@
|
|||
[tox]
|
||||
envlist = py25, py26, py27, py32
|
||||
|
||||
[testenv]
|
||||
commands = nosetests blessings
|
||||
deps = nose
|
||||
changedir = .tox # So Python 3 runs don't pick up incompatible, un-2to3'd source from the cwd
|
Загрузка…
Ссылка в новой задаче