def parse(fd):
return bencode_parse(fd.read(1), fd)
def bencode_parse(c, fd):
if c == "i":
return parse_int(fd)
elif c in "1234567890":
return parse_string(c, fd)
elif c == "l":
return parse_list(fd)
elif c == "d":
return parse_dict(fd)
def parse_int(fd):
buf = []
c = fd.read(1)
while c in "1234567890":
buf.append(c)
c = fd.read(1)
if c != "e":
raise "Bad int delim", c
return int("".join(buf))
def parse_string(c, fd):
buf = [c]
c = fd.read(1)
while c in "1234567890":
buf.append(c)
c = fd.read(1)
if c != ":":
raise "Bad string delim", c
return fd.read(int("".join(buf)))
def parse_list(fd):
contents = []
c = fd.read(1)
while c != "e":
contents.append(bencode_parse(c, fd))
c = fd.read(1)
return contents
def parse_dict(fd):
contents = {}
c = fd.read(1)
while c != "e":
key = bencode_parse(c, fd)
value = parse(fd)
contents[key] = value
c = fd.read(1)
return contents
from StringIO import StringIO
print parse(StringIO("di1e2:ab3:abci56e1:gli2ei3eee"))