#!/usr/bin/env python from __future__ import with_statement import sys import urllib import hashlib from BitTorrent import bencode if not sys.argv[1:]: raise SystemExit('Usage: %s filename.torrent' % sys.argv[0]) with open(sys.argv[1]) as datafile: data = bencode.bdecode(datafile.read()) info_hash = hashlib.sha1(bencode.bencode(data['info'])) magnet = 'magnet:?xt=urn:btih:%(hash)s&dn=%(name)s' % { 'hash': info_hash.hexdigest(), 'name': urllib.quote_plus(data['info']['name']), } try: if 'length' in data['info']: length = data['info']['length'] else: length = sum(i['length'] for i in data['info']['files']) magnet += '&xl=%i' % length except KeyError: pass print magnet