def select_port(default_port=20128):
 import socket
 while True:
  try:
   sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
   sock.bind(('127.0.0.1', default_port))
  except socket.error as _msg:
   default_port += 1
  else:
   break
  finally:
   sock.close()
   sock = None
 return default_port

def select_port ( default_port = 20128 ) : import socket while True : try : sock = socket . socket ( socket . AF_INET , socket . SOCK_STREAM , socket . IPPROTO_TCP ) sock . bind ( ( '127.0.0.1' , default_port ) ) except socket . error as _msg : default_port += 1 else : break finally : sock . close ( ) sock = None return default_port
find and return a non used port .