如何使用python-libtorrent下载特定文件 [英] How to download specific files by using python-libtorrent

查看:298
本文介绍了如何使用python-libtorrent下载特定文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用python-libtorrent实现客户端时 我在GitHub上找到了一个例子

when I use python-libtorrent to implement a client I find an example on GitHub

import libtorrent as lt
import time

ses = lt.session()
ses.listen_on(6881, 6891)


e = lt.bdecode(open("test.torrent", 'rb').read())
info = lt.torrent_info(e)

h = ses.add_torrent(info, "d:\\temp")

while (not h.is_seed()):
    s = h.status()

    state_str = ['queued', 'checking', 'downloading metadata', \
    'downloading', 'finished', 'seeding', 'allocating', 'checking fastresume']
    print s.download_rate
    print '%.2f%% complete (down: %.1f kb/s up: %.1f kB/s peers: %d) %s' % \
            (s.progress * 100, s.download_rate / 1000, s.upload_rate / 1000, \
            s.num_peers, state_str[s.state])

    time.sleep(1)

工作正常.但是它将下载所有包含文件

It works fine. But it will download all the include files

我要让用户选择文件,并且此客户端应仅下载特定文件.

I want ask user to select the files and this client should only download the specific files.

如何?谢谢.

推荐答案

首先,您需要找出哪些片段属于所选文件. 为此,您首先需要找出文件的索引. 这样做就像遍历info.files()一样简单

At first you need to find out which pieces belong to the chosen file/files. In order to do that you first need to find out the index of your file. Doing that is as simple as going through info.files()

i=0
for f in info.files():
    if fileIndex == i:
        fileStr = f
        break
    i += 1

您可以通过打印路径来确认文件正确:

You can confirm that's the correct file by printing its path:

print fileStr.path

现在您需要查找文件到文件的映射并分配优先级(0表示不下载)

Now you need to find the file to piece mapping and assign priorities (0 means don't download)

h = ses.add_torrent(info, "d:\\temp")

pr = info.map_file(fileIndex,0,fileStr.size)
n_pieces = pr.length / info.piece_length() + 1 

for i in range(info.num_pieces()):
    if i in range(pr.piece,pr.piece+n_pieces):
        h.piece_priority(i,7)
    else:
        h.piece_priority(i,0)

现在,您可以像以前一样下载文件.请记住,由于您现在没有像以前那样进入种子模式,因此您现在需要通过检查进度来停止下载:

Now you can download the files as before. Keep in mind that you now need to stop downloading by checking the progress since you do not enter seed mode as before:

while (not h.is_seed()):
    s = h.status()

    state_str = ['queued', 'checking', 'downloading metadata', \
    'downloading', 'finished', 'seeding', 'allocating', 'checking fastresume']
    print s.download_rate
    print '%.2f%% complete (down: %.1f kb/s up: %.1f kB/s peers: %d) %s' % \
            (s.progress * 100, s.download_rate / 1000, s.upload_rate / 1000, \
            s.num_peers, state_str[s.state])

    if s.progress>=1:
        break

    time.sleep(1)

这篇关于如何使用python-libtorrent下载特定文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆