I am writing code to parse tracker information in torrent file using python.
import bencoder
import sys
target = './'+sys.argv[1]
with open(target, 'rb') as torrent_file:
torrent = bencoder.decode(torrent_file.read())
i=0
while True:
try:
print(torrent[b'announce-list'][i])
i+=1
except:
break
The output is as follows.
[b'udp://tracker.openbittorrent.com:80/announce']
[b'udp://tracker.opentrackr.org:1337/announce']
I want to parse the value in the form below.
["tracker.openbittorrent.com", 80]
["tracker.opentrackr.org", 1337]
How should I parse it?
You might use
urllib.parse.urlparse
for this as followsoutput
Explanation: I extract netloc, then split at most once at first from right
b':'
, then apply.decode
to host port to convertbytes
intostr
andint
to convertbytes
intoint
.EDIT: After more careful reading, I noticed that you might access
.hostname
and.port
which allow much more concise code to do that task, that isgives same output as code above.