Use context manager for open in metafile

This commit is contained in:
Calum Lind 2018-05-19 21:03:36 +01:00
parent de2f998218
commit a7c7309027

View File

@ -82,8 +82,6 @@ def make_meta_file(path, url, piece_length, progress=None, title=None, comment=N
info = makeinfo(path, piece_length, progress, name, content_type, private) info = makeinfo(path, piece_length, progress, name, content_type, private)
# check_info(info) # check_info(info)
h = open(f, 'wb')
data['info'] = info data['info'] = info
if title: if title:
data['title'] = title.encode('utf8') data['title'] = title.encode('utf8')
@ -113,9 +111,8 @@ def make_meta_file(path, url, piece_length, progress=None, title=None, comment=N
data['announce-list'] = trackers data['announce-list'] = trackers
data['encoding'] = 'UTF-8' data['encoding'] = 'UTF-8'
with open(f, 'wb') as file_:
h.write(bencode(utf8_encode_structure(data))) file_.write(bencode(utf8_encode_structure(data)))
h.close()
def calcsize(path): def calcsize(path):
@ -154,21 +151,20 @@ def makeinfo(path, piece_length, progress, name=None, content_type=None, private
'content_type': content_type}) # HEREDAVE. bad for batch! 'content_type': content_type}) # HEREDAVE. bad for batch!
else: else:
fs.append({'length': size, 'path': p2}) fs.append({'length': size, 'path': p2})
h = open(f, 'rb') with open(f, 'rb') as file_:
while pos < size: while pos < size:
a = min(size - pos, piece_length - done) a = min(size - pos, piece_length - done)
sh.update(h.read(a)) sh.update(file_.read(a))
done += a done += a
pos += a pos += a
totalhashed += a totalhashed += a
if done == piece_length: if done == piece_length:
pieces.append(sh.digest()) pieces.append(sh.digest())
piece_count += 1 piece_count += 1
done = 0 done = 0
sh = sha() sh = sha()
progress(piece_count, num_pieces) progress(piece_count, num_pieces)
h.close()
if done > 0: if done > 0:
pieces.append(sh.digest()) pieces.append(sh.digest())
piece_count += 1 piece_count += 1
@ -191,16 +187,15 @@ def makeinfo(path, piece_length, progress, name=None, content_type=None, private
pieces = [] pieces = []
p = 0 p = 0
h = open(path, 'rb') with open(path, 'rb') as _file:
while p < size: while p < size:
x = h.read(min(piece_length, size - p)) x = _file.read(min(piece_length, size - p))
pieces.append(sha(x).digest()) pieces.append(sha(x).digest())
piece_count += 1 piece_count += 1
p += piece_length p += piece_length
if p > size: if p > size:
p = size p = size
progress(piece_count, num_pieces) progress(piece_count, num_pieces)
h.close()
name = os.path.split(path)[1].encode('utf8') name = os.path.split(path)[1].encode('utf8')
if content_type is not None: if content_type is not None:
return {'pieces': b''.join(pieces), return {'pieces': b''.join(pieces),