Changeset 414 for pycrash

Show
Ignore:
Timestamp:
05/07/07 10:09:36 (2 years ago)
Author:
athomas
Message:

pycrash: Updated some docstrings, added copyright.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • pycrash/trunk/crash/console.py

    r412 r414  
     1# -*- coding: utf-8 -*- 
     2# 
     3# Copyright (C) 2006 Alec Thomas <alec@swapoff.org> 
     4# 
     5# This software is licensed as described in the file COPYING, which 
     6# you should have received as part of this distribution. 
     7# 
     8 
     9"""Console/terminal interaction classes and functions. 
     10 
     11This module provides a simple formatting syntax for basic terminal visual 
     12control sequences. The syntax is a carat ``^`` followed by a single character. 
     13 
     14Valid formatting controls are: 
     15 
     16``^N`` 
     17    Reset all formatting. 
     18``^B`` 
     19    Toggle bold. 
     20``^U`` 
     21    Toggle underline. 
     22``^0`` 
     23    Set black foreground. 
     24``^1`` 
     25    Set red foreground. 
     26``^2`` 
     27    Set green foreground. 
     28``^3`` 
     29    Set brown foreground. 
     30``^4`` 
     31    Set blue foreground. 
     32``^5`` 
     33    Set magenta foreground. 
     34``^6`` 
     35    Set cyan foreground. 
     36``^7`` 
     37    Set white foreground. 
     38 
     39""" 
     40 
    141import re 
    242import sys 
    343import os 
    444import codecs 
     45 
    546 
    647_decode_re = re.compile(r'''[^^]+|\^([N0-7BU])''') 
     
    950_cwrap_re = re.compile(r'''(\n)|(\s+)|((?:\^[N0-7BU]|\S)+\b[^\n^\w]*)''') 
    1051_colour_terminal = 0 
     52 
    1153 
    1254try: 
     
    72114        self.underline = False 
    73115 
     116 
    74117class CodecStreamWriter(Codec, codecs.StreamWriter): 
    75118    def __init__(self, stream, errors='strict'): 
     
    86129            self.write('\n') 
    87130 
     131 
    88132class CodecStreamReader(Codec, codecs.StreamReader): 
    89133    def __init__(self, stream, errors='strict'): 
     
    104148        self.reset() 
    105149 
     150 
    106151def decode(input, errors='strict'): 
    107152    return (Codec(errors=errors).decode(input), len(input)) 
    108153 
     154 
    109155def encode(input, errors='strict'): 
    110156    return (Codec(errors=errors).encode(input), len(input)) 
    111157 
     158 
    112159def register_codec(): 
     160    """Register the 'console' codec with Python. 
     161 
     162    The formatting syntax can then be used like any other codec: 
     163 
     164    >>> register_codec() 
     165    >>> '^Bbold^B'.decode('console') 
     166    '\\x1b[1mbold\\x1b[22m' 
     167    >>> '\\x1b[1mbold\\x1b[22m'.encode('console') 
     168    '^Bbold^B' 
     169    """ 
    113170    def inner_register(encoding): 
    114171        if encoding != 'console': 
     
    117174    return codecs.register(inner_register) 
    118175 
     176 
    119177def colour_cwrite(io, text): 
    120     io.write(decode(text)) 
     178    """Decode text to ANSI escape sequences and write to the io object.""" 
     179    io.write(decode(text)[0]) 
     180 
    121181 
    122182def mono_cwrite(io, text): 
     183    """Strip all colour encoding and write to io.""" 
    123184    io.write(_cprint_strip.sub('', text)) 
    124185 
     
    133194^N is reset to normal text. Colour is not automatically reset at the 
    134195end of output. 
     196 
     197If ``sys.stdout`` is not a TTY, colour codes will be stripped. 
    135198""" 
    136      
     199 
     200 
    137201def cprint(*args): 
     202    """Emulate the ``print`` builtin, with terminal shortcuts.""" 
    138203    stream = sys.stdout 
    139204    if args and type(args[0]) is file: 
     
    142207    cwrite(stream, ' '.join(args) + '\n') 
    143208 
     209 
    144210def cprintstrip(*args): 
     211    """As with cprint, but strip colour codes.""" 
    145212    return _cprint_strip.sub('', ' '.join(map(str, args))) 
    146213 
     214 
    147215def clen(arg): 
     216    """Return the length of arg after colour codes are stripped.""" 
    148217    return len(cprintstrip(arg)) 
     218 
    149219 
    150220def error(*args): 
    151221    """Print a red error message prefixed by ERR.""" 
    152222    cprint(sys.stderr, "^1^BERR " + ' '.join(map(str, args)) + '^N') 
     223 
    153224 
    154225def fatal(*args): 
     
    157228    sys.exit(-1) 
    158229 
     230 
    159231def warning(*args): 
    160232    """Print a yellow warning message prefixed by WRN""" 
    161233    cprint(sys.stderr, "^3^BWRN " + ' '.join(map(str, args)) + '^N') 
    162234 
     235 
    163236def info(*args): 
    164237    """Print a green notice prefixed by INF.""" 
    165238    cprint("^2^BINF ^B" + ' '.join(map(str, args)) + '^N') 
     239 
    166240 
    167241def termwidth(): 
     
    172246        return int(os.environ.get('COLUMNS', 80)) 
    173247 
     248 
    174249def termheight(): 
    175250    """Guess the current terminal height.""" 
     
    178253    except: 
    179254        return int(os.environ.get('LINES', 25)) 
     255 
    180256 
    181257def csplice(text, start=0, end=-1): 
     
    208284    return out 
    209285 
     286 
    210287def cwraptext(rtext, width=termwidth(), subsequent_indent=''): 
    211288    """Wrap multi-line text to width (defaults to termwidth())""" 
     
    239316    return out 
    240317 
     318 
    241319def wraptoterm(text, **kwargs): 
    242320    """Wrap the given text to the current terminal width""" 
    243321    return '\n'.join(cwraptext(text, **kwargs)) 
     322 
    244323 
    245324def rjustify(text, width=termwidth()): 
     
    251330    return out.rstrip() 
    252331 
     332 
    253333def cjustify(text, width=termwidth()): 
    254334    """Centre the given text.""" 
     
    259339    return out.rstrip() 
    260340 
     341 
    261342def print_table(header, table, sep=' ', auto_format=('^B^U', '^6', '^B^6'), expand_to_fit=1): 
    262343    """Print a list of lists as a table, so that columns line up nicely. 
    263     header, if specified, will be printed as the first row. sep is the 
    264     separator between columns. 
    265  
    266     auto_format is a tuple specifying the formatting colours to use for each 
    267     row. The first element is the header colour, subsequent elements are 
    268     for alternating rows. eg. ('^B', '^1', '^2') 
    269  
    270     expand_to_fit signifies whether print_table should expand the table to the 
    271     width of the terminal. 
    272  
    273     Note: print_table supports the ^R formatting code, in addition to those 
    274     supported by cprint, which corresponds to the colour formatting of the 
    275     current table row.""" 
     344 
     345 
     346 
     347    ``header``: list of column headings 
     348        Will be printed as the first row. 
     349 
     350    ``table``: list of rows 
     351        Data to print. 
     352 
     353    ``sep=' '`` 
     354        The column separator. 
     355 
     356    ``auto_format=('^B^U', '^6', '^B^2')``: tuple 
     357        A tuple specifying the formatting colours to use for each row. The 
     358        first element is the header colour, subsequent elements are for 
     359        alternating rows. 
     360 
     361    ``expand_to_fit=True``: boolean 
     362        Signifies whether print_table should expand the table to the width of 
     363        the terminal. 
     364 
     365    Note: ``print_table`` supports the ``^R`` formatting code, in addition to 
     366    those supported by cprint, which corresponds to the colour formatting of 
     367    the current table row.""" 
    276368    def ctlen(s): 
    277369        return clen(s.replace('^R', '')) 
     
    296388                colwidths[0] += termwidth() - sum(colwidths) 
    297389 
    298     auto_format = auto_format[:] 
     390    auto_format = list(auto_format) 
    299391 
    300392    rowalt = -1 
     
    334426    import msvcrt 
    335427    def getch(): 
     428        """Get a single character from the terminal.""" 
    336429        return msvcrt.getch() 
    337430except ImportError: 
     
    339432 
    340433    def getch(): 
     434        """Get a single character from the terminal.""" 
    341435        fd = sys.stdin.fileno() 
    342436        old_settings = termios.tcgetattr(fd) 
     
    349443 
    350444getch.__doc__ = " Read a single character from stdin. " 
     445 
     446 
     447if __name__ == '__main__': 
     448    import doctest 
     449    doctest.testmod()