How To/python/MyMiscUtils/

# -*- coding: utf-8 -*-
 
class StropError(Exception):
    pass
 
safeDecodeErrors = []
 
def nl2space(q):
    """ converts multiline sql into one-line sql """
    q = q.replace('\r\n', ' ')
    q = q.replace('\r', ' ')
    return q.replace('\n', ' ')
 
def htmlEscape(text):
    """
    htmlEscape(string text) -> string
    Produce entities within text.
 
    [en] works like php htmlspecialchars(). See also http://wiki.python.org/moin/EscapingHtml
    [pl] działa jak htmlspecialchars w php. Zobacz też (link powyzej)/
    """
    html_escape_table = {
    "&": "&",
    '"': """,
    "'": "'",
    ">": ">",
    "<": "&lt;",
    }
    L=[]
    for c in text:
        L.append(html_escape_table.get(c,c))
    return "".join(L)
 
def safeDecode(s, encoding='utf8', replacement='_', limit=100):
    """
    Tries to decode [s] string using encoding. When impossible to convert bytes
    are found those bytes are replaced with [replacement]. [limit] describes how
    many chars can be converted. When [limit] is reached StringopError exception
    is raised.
    """
    del safeDecodeErrors[:]
    while 1: 
        try:
            return s.decode(encoding)
        except UnicodeDecodeError:
            err = {}
            err['in'] = s
            e = sys.exc_info()[1]
            s = ''.join([s[0:e.start], replacement, s[e.end:]])
            err['out'] = s
            err['start'] = e.start
            err['end'] = e.end
            safeDecodeErrors.append(err)
        limit -= 1
        if limit == 0:
            raise StropError('Maximum limit of %s changes achieved.' % limit)
 
'''
Example:
>>> print asHex('abcdef')
\x61\x62\x63\x64\x65\x66
'''
def asHex(str):
    """ Print string as hex code in python """
    return ''.join(["\\x%02X" % ord(c) for c in str])