Welcome to portend documentation!

A simple library for managing the availability of ports.

class portend.Checker(timeout=1.0)

Bases: object

assert_free(host, port=None)

Assert that the given addr is free in that all attempts to connect fail within the timeout or raise a PortNotFree exception.

>>> free_port = find_available_local_port()
>>> Checker().assert_free('localhost', free_port)
>>> Checker().assert_free('127.0.0.1', free_port)
>>> Checker().assert_free('::1', free_port)

Also accepts an addr tuple

>>> addr = '::1', free_port, 0, 0
>>> Checker().assert_free(addr)

Host might refer to a server bind address like ‘::’, which should use localhost to perform the check.

>>> Checker().assert_free('::', free_port)
class portend.HostPort

Bases: str

A simple representation of a host/port pair as a string

>>> hp = HostPort('localhost:32768')
>>> hp.host
'localhost'
>>> hp.port
32768
>>> len(hp)
15
>>> hp = HostPort('[::1]:32768')
>>> hp.host
'::1'
>>> hp.port
32768
classmethod from_addr(addr)
property host
property port
exception portend.PortNotFree

Bases: OSError

exception portend.Timeout

Bases: OSError

portend.client_host(server_host)

Return the host on which a client can connect to the given listener.

>>> client_host('192.168.0.1')
'192.168.0.1'
>>> client_host('0.0.0.0')
'127.0.0.1'
>>> client_host('::')
'::1'
portend.find_available_local_port()

Find a free port on localhost.

>>> 0 < find_available_local_port() < 65536
True
portend.free(host, port, timeout=inf)

Wait for the specified port to become free (dropping or rejecting requests). Return when the port is free or raise a Timeout if timeout has elapsed.

Timeout may be specified in seconds or as a timedelta. If timeout is None or ∞, the routine will run indefinitely.

>>> free('localhost', find_available_local_port())
>>> free(None, None)
Traceback (most recent call last):
...
ValueError: Host values of '' or None are not allowed.
portend.occupied(host, port, timeout=inf)

Wait for the specified port to become occupied (accepting requests). Return when the port is occupied or raise a Timeout if timeout has elapsed.

Timeout may be specified in seconds or as a timedelta. If timeout is None or ∞, the routine will run indefinitely.

>>> occupied('localhost', find_available_local_port(), .1)
Traceback (most recent call last):
...
Timeout: Port ... not bound on localhost.
>>> occupied(None, None)
Traceback (most recent call last):
...
ValueError: Host values of '' or None are not allowed.

Indices and tables