如何提取给定目录的名称?洪流'将创建从底层的代码数据?



在python中解析bencode以获得.torrent文件生成的目录名的最简单方法是什么?

.torrent文件名和它们生成的目录名很少相同。我正在开发一个应用程序,将.torrent文件交给服务器,并在完成后检索它。我需要知道.torrent文件创建的文件的名称,而不需要实际启动下载。我不能在服务器端执行任何操作。

以前,我通过一个完整的torrent客户端(libtorrent)的相当庞大的依赖实现了这一点。这已不再可行。遗憾的是,我不够聪明,无法理解libtorrent是如何解决这个问题的,但是获取文件名的命令是:

import libtorrent as lt
TORRENT = <direntry item that is a .torrent file>

def getFileNamefromTorrent(torrent):
"""must be a direntry item. Gets the name of the torrent's finished folder from the .torrent file."""
torrent_info = lt.torrent_info(torrent.path)
return torrent_info.name()
print(getFileNameFromTorrent(TORRENT)

我的第一次尝试是解析bencode,在那里我可以得到文件名:

import bencode
import itertools
TORRENT = "path to .torrent file"
def getTorrentFilenames(filename):
with open(filename, "rb") as fin:
torrent = bencode.bdecode(fin.read())

return itertools.chain(*(f["path"] for f in torrent["info"]["files"]))
for file in getTorrentFilenames(TORRENT) 

这给了我种子里面的文件,但是没有提供它存放这些文件的目录名。

我尝试访问字典中的不同元素(如name而不是files),但产生typeError

Traceback (most recent call last):
File "torrent_management.py", line 65, in <module>
test = listTorrent(TESTTORRENT)
File "torrent_management.py", line 63, in listTorrent
return itertools.chain(*(f["path"] for f in torrent["info"]["name"]))
File "torrent_management.py", line 63, in <genexpr>
return itertools.chain(*(f["path"] for f in torrent["info"]["name"]))
TypeError: string indices must be integers
如果我忽略了一些非常明显的事情,我道歉。BitTorrent .torrent元文件结构提到有一个"名称"。在字典里。

我在上面的代码节中提供了一个在python中运行的最小工作示例。字典应该提供以bencode编码的种子名称,但它不是一个有效的字典项。

我知道我错在哪里了。

正确的最小解如下:(如果您在使用bencode库时遇到问题,请确保使用bencode.py而不是bencode

import bencode
def getTorrentName(filename):
"""List name of a torrent from the corresponding .torrent file."""
with open(filename, "rb") as fin:
torrent = bencode.bdecode(fin.read())

return torrent["info"]["name"]
torrent = <location of .torrent>
torrentName = getTorrentName(torrent)

而且,很显然,名字"关键是严格建议。我不确定"名字"是否;Key用于生成相应的目录,或者只是与其关联。我很想知道!

最新更新