Last active
November 11, 2022 01:42
-
-
Save wonderbeyond/4b8c3e17c84905eb1db5c949b5a84e6c to your computer and use it in GitHub Desktop.
Waiting for a TCP port ready to accept connections
This file contains hidden or 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
"""Thanks to https://gist.github.com/butla/2d9a4c0f35ea47b7452156c96a4e7b12""" | |
import socket | |
import time | |
def wait_port_ready(port: int, host: str = 'localhost', timeout: float = 5.0): | |
""" | |
Wait until a port starts accepting TCP connections. | |
Args: | |
port: Port number. | |
host: Host address on which the port should exist. | |
timeout: 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 e: | |
time.sleep(0.01) | |
if time.perf_counter() - start_time >= timeout: | |
raise TimeoutError( | |
f'Waited too long for `{host}:{port}` ready to accept connections.' | |
) from e |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment