如何完全跳过使用 libtorrent 下载将文件写入磁盘?

How to completely skip writing files to disk with libtorrent downloads?

我有以下代码可以从磁力 URI 下载 torrent。

#python
#lt.storage_mode_t(0) ## tried this, didnt work
ses = lt.session()
params = { 'save_path': "/save/here"}

ses.listen_on(6881,6891)
ses.add_dht_router("router.utorrent.com", 6881)

#ses = lt.session()
link = "magnet:?xt=urn:btih:395603fa..hash..."
handle = lt.add_magnet_uri(ses, link, params)
while (not handle.has_metadata()):
    time.sleep(1)
handle.pause () # got meta data paused, and set priority
handle.file_priority(0, 1)
handle.file_priority(1,0)
handle.file_priority(2,0)
print handle.file_priorities()
#output is [1,0,0]
#i checked no files written into disk yet.
handle.resume()
while (not handle.is_finished()):
    time.sleep(1) #wait until download 

有效,但是在这个特定的 torrent 中,有 3 个文件,文件 0 - 2 kb,文件 1 - 300mb,文件 3 - 2kb。

从代码中可以看出,文件0的优先级为1,其余文件的优先级为0(即不下载)。

问题是当 0 文件下载完成后,我想让它停止,不再下载。但它有时会下载 1 个文件 - 部分,有时 100mb 或 200mb,有时几 kb,有时整个文件。

所以我的问题是:如何确保只下载文件 0,而不是 1 和 2。

编辑:我添加了一个检查是否有元数据,然后设置优先级然后恢复它,但是这仍然会部分下载第二个文件。

发生这种情况的原因是添加 torrent(开始下载)和设置文件优先级之间的竞争。

为避免这种情况,您可以在添加 torrent 的同时设置文件优先级,如下所示:

p = parse_magnet_uri(link)
p['file_priorities'] = [1, 0, 0]
handle = ses.add_torrent(p)

更新:

您不需要知道文件的数量,为比最终出现在 torrent 文件中的文件更多的文件提供文件优先级是可以的。其余的将被忽略。但是,如果您不想从 swarm 下载任何东西(元数据/.torrent 除外),更好的方法是设置 flag_upload_mode 标志。参见 documentation

p = parse_magnet_uri(link)
p['flags'] |= add_torrent_params_flags_t.flag_upload_mode
handle = ses.add_torrent(p)