If you only need to find a free port for later use, here is a snippet similar to a previous answer, but shorter, using socketserver:
import socketserver
with socketserver.TCPServer(("localhost", 0), None) as s:
free_port = s.server_address[1]
Note that the port is not guaranteed to remain free, so you may need to put this snippet and the code using it in a loop.