-
-
Save shuklalok/358b9819cb92be9af0f546822a546cba to your computer and use it in GitHub Desktop.
Waiting for a TCP port to start accepting connections (Python 3)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import socket | |
def wait_for_port(port, host='localhost', timeout=5.0): | |
"""Wait until a port starts accepting TCP connections. | |
Args: | |
port (int): Port number. | |
host (str): Host address on which the port should exist. | |
timeout (float): In seconds. How long to wait before raising errors. | |
Raises: | |
TimeoutError: The port isn't accepting connection after time specified in `timeout`. | |
""" | |
start_time = time.perf_counter() | |
while True: | |
try: | |
with socket.create_connection((host, port), timeout=timeout): | |
break | |
except OSError as ex: | |
time.sleep(0.01) | |
if time.perf_counter() - start_time >= timeout: | |
raise TimeoutError('Waited too long for the port {} on host {} to start accepting ' | |
'connections.'.format(port, host)) from ex |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment