Exemple #1
0
def write(sexp, out=sys.stdout):
    """Write an S-expression to a file"""

    if isinstance(sexp, Sym):
        out.write(sexp)

    elif isinstance(sexp, basestring):
        out.write('"' + quote(sexp) + '"')

    elif isinstance(sexp, bool):
        if sexp:
            out.write("#t")
        else:
            out.write("#f")

    elif isinstance(sexp, (int, float)):
        out.write(repr(sexp))

    elif hasattr(sexp, "__iter__"):
        # write list

        out.write("(")
        size = len(sexp)
        it = iter(sexp)
        try:
            a = it.next()
            while True:
                write(a, out)
                a = it.next()
                out.write(" ")
        except StopIteration:
            pass
                
        out.write(")")

    else:
        raise Exception("item with unknown type in sexp '%s'" % repr(sexp))
Exemple #2
0
def write_pretty(sexp, out=sys.stdout, 
                 _prefix=0, _first=True):
    """Write an S-expression to a file"""

    if _first:
        out.write(" " * _prefix)

    if isinstance(sexp, Sym):
        out.write(sexp)
        return len(sexp)

    elif isinstance(sexp, basestring):
        s = '"' + quote(sexp) + '"'
        out.write(s)
        return len(s)

    elif isinstance(sexp, bool):
        if sexp:
            out.write("#t")
        else:
            out.write("#f")
        return 2

    elif isinstance(sexp, (int, float)):
        s = repr(sexp)
        out.write(s)
        return len(s)

    elif hasattr(sexp, "__iter__"):
        # write list

        i = 0
        out.write("(")
        size = 1
        size2 = 0
        it = iter(sexp)
        _prefix += 1
        try:
            a = it.next()
            while True:
                if i < 1:
                    sexp_size = write_pretty(a, out, 
                                             _prefix=_prefix, _first=False)
                    i += 1
                    size += sexp_size
                    _prefix += sexp_size
                    a = it.next()
                    out.write(" ")
                    size += 1
                    _prefix += 1
                else:
                    size2 = write_pretty(a, out, 
                                         _prefix=_prefix, _first=(i >= 2))
                    i += 1
                    a = it.next()
                    out.write("\n")
                    
        except StopIteration:
            pass
                
        out.write(")")
        return size + size2 + 1

    else:
        raise Exception("item with unknown type in sexp '%s'" % repr(sexp))