You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python版LibTorrent在上传前获取分发数据?

用Python版LibTorrent获取Torrent分发数据的操作步骤

1. 安装LibTorrent Python绑定

先安装对应版本的Python绑定,优先用pip安装:

pip install libtorrent

Linux系统也可通过包管理器安装(如apt install python3-libtorrent),稳定性更优。

2. 初始化LibTorrent会话

创建会话对象,配置基础参数,禁用自动下载以避免不必要的文件写入:

import libtorrent as lt

session = lt.session()
session.listen_on(6881, 6891)
# 限制下载速率为0,仅获取元数据与分发信息
session.set_download_rate_limit(0)

3. 加载Torrent源(两种场景)

场景A:从本地.torrent文件加载

读取torrent文件生成torrent_info对象,再添加到会话:

# 读取本地torrent文件
with open("your_torrent_file.torrent", "rb") as f:
    torrent_info = lt.torrent_info(f.read())

# 添加到会话,save_path仅用于占位,不会实际下载
handle = session.add_torrent({"ti": torrent_info, "save_path": "./temp"})

场景B:从磁力链接加载

磁力链接需先获取完整元数据,设置参数后等待元数据同步完成:

magnet_link = "magnet:?xt=urn:btih:..."
params = {
    "url": magnet_link,
    "save_path": "./temp",
    "storage_mode": lt.storage_mode_t.storage_mode_sparse
}
handle = session.add_torrent(params)

# 等待元数据获取完成
print("正在获取种子元数据...")
while not handle.has_metadata():
    import time
    time.sleep(1)
torrent_info = handle.get_torrent_info()

4. 获取各类分发数据

元数据就绪后,可提取以下核心分发相关信息:

  • 基础种子属性
print(f"种子名称: {torrent_info.name()}")
print(f"总文件大小: {torrent_info.total_size() / (1024*1024):.2f} MB")
print(f"Info哈希值: {torrent_info.info_hash()}")
  • 网络节点分发状态
status = handle.status()
print(f"当前连接节点数: {status.num_peers}")
print(f"在线种子数(Seeds): {status.num_seeds}")
print(f"在线下载者数(Peers): {status.num_peers - status.num_seeds}")
print(f"已获取分片数: {status.num_pieces} / {torrent_info.num_pieces()}")
  • 节点详细信息
peers = handle.get_peer_info()
for peer in peers:
    print(f"节点地址: {peer.ip}:{peer.port} | 上传速度: {peer.upload_rate / 1024:.2f} KB/s | 下载速度: {peer.download_rate / 1024:.2f} KB/s")
  • 多文件种子的文件列表
files = torrent_info.files()
for file in files:
    print(f"文件路径: {file.path} | 文件大小: {file.size / (1024*1024):.2f} MB")

5. 清理资源

完成数据获取后,移除torrent并关闭会话:

session.remove_torrent(handle)
session.stop()

注意:save_path为必填参数,但由于设置了下载限速为0,不会实际下载文件;稀疏存储模式仅创建空文件占位,不会占用磁盘空间。


内容的提问来源于stack exchange,提问作者Wintreist

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 17:30:12