From 83864aa9c860a42b4a93e3da4783976a038e92e4 Mon Sep 17 00:00:00 2001 From: Prodesire Date: Sat, 3 Feb 2018 00:28:07 +0800 Subject: [PATCH] refactor network.get_free_port with closing context --- pydu/network.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/pydu/network.py b/pydu/network.py index f00b578..6986e0e 100644 --- a/pydu/network.py +++ b/pydu/network.py @@ -2,6 +2,8 @@ import socket import struct import ctypes import binascii +from contextlib import closing + from .platform import WINDOWS from .string import safeencode, safeunicode from .convert import hex2dec, dec2hex @@ -113,10 +115,9 @@ def is_ipv6(ip): def get_free_port(): - s = socket.socket(socket.AF_INET, type=socket.SOCK_STREAM) - s.bind(('127.0.0.1', 0)) - _, port = s.getsockname() - s.close() + with closing(socket.socket(socket.AF_INET, type=socket.SOCK_STREAM)) as s: + s.bind(('127.0.0.1', 0)) + _, port = s.getsockname() return port