前天,在 Python将BT种子文件转换为磁力链的两种方法 篇中根据网上的方法完成后bt种子转换为磁力链的过程,今天要做的是一个反过程,将磁力链转化为种子文件。

1、需要先安装python-libtorrent包 ,在ubuntu环境下,可以通过以下指令完成安装:

1# sudo apt-get install python-libtorrent

2、代码如下:

 1#!/usr/bin/env python
 2import shutil
 3import tempfile
 4import os.path as pt
 5import sys
 6import libtorrent as lt
 7from time import sleep
 8def magnet2torrent(magnet, output_name=None):
 9    if output_name and \
10            not pt.isdir(output_name) and \
11            not pt.isdir(pt.dirname(pt.abspath(output_name))):
12        print("Invalid output folder: " + pt.dirname(pt.abspath(output_name)))
13        print("")
14        sys.exit(0)
15    tempdir = tempfile.mkdtemp()
16    ses = lt.session()
17    params = {
18        'save_path': tempdir,
19        'duplicate_is_error': True,
20        'storage_mode': lt.storage_mode_t(2),
21        'paused': False,
22        'auto_managed': True,
23        'duplicate_is_error': True
24    }
25    handle = lt.add_magnet_uri(ses, magnet, params)
26    print("Downloading Metadata (this may take a while)")
27    while (not handle.has_metadata()):
28        try:
29            sleep(1)
30        except KeyboardInterrupt:
31            print("Aborting...")
32            ses.pause()
33            print("Cleanup dir " + tempdir)
34            shutil.rmtree(tempdir)
35            sys.exit(0)
36    ses.pause()
37    print("Done")
38    torinfo = handle.get_torrent_info()
39    torfile = lt.create_torrent(torinfo)
40    output = pt.abspath(torinfo.name() + ".torrent")
41    if output_name:
42        if pt.isdir(output_name):
43            output = pt.abspath(pt.join(
44                output_name, torinfo.name() + ".torrent"))
45        elif pt.isdir(pt.dirname(pt.abspath(output_name))):
46            output = pt.abspath(output_name)
47    print("Saving torrent file here : " + output + " ...")
48    torcontent = lt.bencode(torfile.generate())
49    f = open(output, "wb")
50    f.write(lt.bencode(torfile.generate()))
51    f.close()
52    print("Saved! Cleaning up dir: " + tempdir)
53    ses.remove_torrent(handle)
54    shutil.rmtree(tempdir)
55    return output
56def showHelp():
57    print("")
58    print("USAGE: " + pt.basename(sys.argv[0]) + " MAGNET [OUTPUT]")
59    print("  MAGNET\t- the magnet url")
60    print("  OUTPUT\t- the output torrent file name")
61    print("")
62def main():
63    if len(sys.argv) = 3:
64        output_name = sys.argv[2]
65    magnet2torrent(magnet, output_name)
66if __name__ == "__main__":
67    main()

3、用法如下

1# python Magnet_To_Torrent2.py <magnet link=""> [torrent file]</magnet>

以上这段代码非原创,来自于github上。