I've been using python to download torrents for some time but for about a week or more, those torrent files have stopped opening in transmission. Here is the code:

torrent = urllib2.urlopen(torrent URL, timeout = 30)
output = open('mytorrent.torrent', 'wb')

This used to work fine in the past but now it won't load in transmission. I tried another client 'tixati' which threw up an error "error parsing meta-file". If I download the torrent file via browser, it opens fine in both clients. I've tried changing file options to output = open('mytorrent.torrent', 'w') but the result is the same.

Anybody have any ideas?

  • Have you diffed the browser and Python versions of the same torrent? – Oli Jun 3 '13 at 9:10
  • how do i diff b/w them? these files don't contain text and cannot be opened by a text editor. gedit shows gibberish when i try to open both original and self-created files. – koogee Jun 3 '13 at 10:26
  • A fair point. I forgot they were binary data. You could convert them to hex for comparison but it's going to become harder to spot what the original difference was. I suspect Python is encoding them as something they're not intended to be. – Oli Jun 3 '13 at 11:08
  • Could this be the same issue as mentioned in this question: Downloading a torrent file with WebClient, results in corrupt file ? – koogee Jun 3 '13 at 11:15
  • Ok, i can confirm its the same problem as mentioned in the question link above. although the torrent url ends with '.torrent' suffix, it is actually zipped with gzip. Once I unzip the downloaded file using gunzip, the torrent file starts working normally. I need to code python to look up file encoding and unzip the file using the appropriate tool...How do I do that? – koogee Jun 3 '13 at 11:25

urllib2 does exactly what it's told and won't automatically decompress content streams. Thankfully, that bit isn't too hard.

Additionally if you're always using the same server, you could skip the check for gzip encoding.

from io import BytesIO
import gzip

torrent = urllib2.urlopen(torrentURL, timeout=30)
buffer = BytesIO(torrent.read())
gz = gzip.GzipFile(fileobj=buffer)
output = open('mytorrent.torrent', 'wb')

I've subbed in io.BytesIO to keep this compatible with Python 3.

  • Traceback (most recent call last): File "unzip_torrent.py", line 13, in <module> output.write(gz.read()) File "/usr/lib/python2.7/gzip.py", line 249, in read self._read(readsize) File "/usr/lib/python2.7/gzip.py", line 283, in _read pos = self.fileobj.tell() # Save current position AttributeError: addinfourl instance has no attribute 'tell' – koogee Jun 3 '13 at 14:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.