Example #1
0
def get_lines_from_file(filename, lineno, context=0, globals=None):
    """Return `content` number of lines before and after the specified
    `lineno` from the (source code) file identified by `filename`.

    Returns a `(lines_before, line, lines_after)` tuple.
    """
    # The linecache module can load source code from eggs since Python 2.6.
    # Prior versions return lines from the wrong file, so we try locating
    # the file in eggs manually first.
    lines = []
    match = _egg_path_re.match(filename)
    if match:
        import zipfile
        for path in sys.path:
            try:
                zip = zipfile.ZipFile(path, 'r')
                try:
                    lines = zip.read(match.group(1)).splitlines()
                    break
                finally:
                    zip.close()
            except Exception:
                pass

    if not lines:
        import linecache
        linecache.checkcache(filename)
        if arity(linecache.getlines) >= 2:
            lines = linecache.getlines(filename, globals)
        else:   # Python 2.4
            lines = linecache.getlines(filename)

    if not 0 <= lineno < len(lines):
        return (), None, ()
    lbound = max(0, lineno - context)
    ubound = lineno + 1 + context

    charset = None
    rep = re.compile('coding[=:]\s*([-\w.]+)')
    for linestr in lines[:2]:
        match = rep.search(linestr)
        if match:
            charset = match.group(1)
            break

    before = [to_unicode(l.rstrip('\n'), charset)
                 for l in lines[lbound:lineno]]
    line = to_unicode(lines[lineno].rstrip('\n'), charset)
    after = [to_unicode(l.rstrip('\n'), charset) \
                 for l in lines[lineno + 1:ubound]]

    return before, line, after
Example #2
0
    def _send_cookie_headers(self):
        for name in self.outcookie.keys():
            path = self.outcookie[name].get("path")
            if path:
                path = path.replace(" ", "%20").replace(";", "%3B").replace(",", "%3C")
            self.outcookie[name]["path"] = path

        cookies = to_unicode(self.outcookie.output(header="")).encode("utf-8")
        for cookie in cookies.splitlines():
            self._outheaders.append(("Set-Cookie", cookie.strip()))
Example #3
0
def get_doc(obj):
    """Return the docstring of an object as a tuple `(summary, description)`,
    where `summary` is the first paragraph and `description` is the remaining
    text.
    """
    doc = inspect.getdoc(obj)
    if not doc:
        return (None, None)
    doc = to_unicode(doc).split('\n\n', 1)
    summary = doc[0].replace('\n', ' ')
    description = len(doc) > 1 and doc[1] or None
    return (summary, description)
Example #4
0
def get_last_traceback():
    import traceback
    from StringIO import StringIO
    tb = StringIO()
    traceback.print_exc(file=tb)
    return to_unicode(tb.getvalue())