Skip to content

Instantly share code, notes, and snippets.

@shuklalok
Forked from butla/wait_for_tcp_port.py
Created March 23, 2021 06:53
Show Gist options
  • Save shuklalok/358b9819cb92be9af0f546822a546cba to your computer and use it in GitHub Desktop.
Save shuklalok/358b9819cb92be9af0f546822a546cba to your computer and use it in GitHub Desktop.
Waiting for a TCP port to start accepting connections (Python 3)
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