Search code examples
pythonpython-3.xbittorrentlibtorrent

download content torrent files point to in python3


Perhaps I'm misunderstanding how .torrent files work, but is there a way in python to download the actual referenced content the .torrent file points to that would be downloaded say using a torrent client such as utorrent, but from the shell/command line using python?

The following works for simply downloading a .torrent file and sure I could open the torrent client as well do download the .torrent, but I'd rather streamline the process in the command line. Can't seem to find much online about doing this...

torrent = torrentutils.parse_magnet(magnet)
infohash = torrent['infoHash']
session = requests.Session()
session.headers.update({'User-Agent': 'Mozilla/5.0'})
url = "http://torcache.net/torrent/" + infohash + ".torrent"
answer = session.get(url)
torrent_data = answer.content
buffer = BytesIO(torrent_data)
gz = gzip.GzipFile(fileobj = buffer)
output = open(torrent['name'], "wb")
output.write(torrent_data)

As far as I know i can't use libtorrent for python3 on a 64 bit windows os.


Solution

  • If magnet: links work in your web browser then a simple way to start a new torrent download from your Python script is to open the url using your web browser:

    import webbrowser
    
    webbrowser.open(magnet_link)
    

    Or from the command-line:

    $ python -m webbrowser "magnet:?xt=urn:btih:ebab37b86830e1ed624c1fdbb2c59a1800135610&dn=StackOverflow201508.7z"
    

    The download is performed by your actual torrent client such as uTorrent.