Bencode.py

4.0.0 · active · verified Thu Apr 16

Bencode.py is a simple bencode parser for Python, compatible with Python 2, Python 3, and PyPy. Version 4.0.0 is the current stable release, which refactored the API into a new module, `bencodepy`. The library provides an intuitive API for encoding and decoding Bencode data, a serialization format primarily used in BitTorrent, and maintains an active release cadence.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to encode Python dictionaries, integers, and lists into bencode format, and then decode bencoded bytes back into Python data structures. It also shows how to configure `bencodepy` to decode strings as UTF-8 rather than raw bytes.

import bencodepy

# Encode Python data to bencode bytes
data_to_encode = {
    'message': 'hello world',
    'number': 123,
    'list_of_items': ['item1', 2, b'binary_data']
}
bencoded_data = bencodepy.encode(data_to_encode)
print(f"Encoded: {bencoded_data}")

# Decode bencode bytes to Python data
decoded_data = bencodepy.decode(bencoded_data)
print(f"Decoded: {decoded_data}")

# Decode to UTF-8 strings by default using a custom Bencode instance
bc = bencodepy.Bencode(encoding='utf-8')
utf8_decoded = bc.decode(b'd7:message11:hello worlde')
print(f"UTF-8 Decoded: {utf8_decoded}')

view raw JSON →