Pick unused port on OS. Race condition might occur after close().
import socket def pick_unused(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('localhost', 0)) addr, port = s.getsockname() s.close() return port