Skip to content

API Reference

This page documents the public API of the portly package. The Python functions are thin wrappers over a native Rust core; see the Development page for how the two layers fit together.

Exceptions

All errors raised by portly derive from PortlyError. The concrete subclasses are also subclasses of the builtin OSError / PermissionError, so existing handlers keep working.

Bases: Exception

Base class for all portly errors.

Bases: PortlyError, OSError

A port-related failure (invalid port, no free port found).

Also a subclass of :class:OSError, so existing except OSError handlers keep working.

Bases: PortlyError, PermissionError

Permission denied while inspecting or killing a process.

Also a subclass of :class:PermissionError, so existing except PermissionError handlers keep working.

Functions

Return True if port is free on localhost, False otherwise.

Return a free port, preferring preferred when it is free.

Raises:

Type Description
PortlyPortError

If no free port could be found.

Return free port(s) within the inclusive range [lo, hi].

Returns a single port number when count is 1, otherwise a list of distinct free ports.

Raises:

Type Description
ValueError

If lo == 0 or lo > hi.

PortlyPortError

If fewer than count free ports exist in the range.

Wait up to timeout seconds for port to become free.

Returns True if the port became free, False on timeout.

Wait up to timeout seconds for a server to accept connections on port.

Polls host:port with TCP connect attempts every interval seconds. Returns True once the port accepts a connection, False on timeout.

Return information about the process listening on port.

Returns None if the port is free (or its owner is not visible to us).

Kill the process(es) using port.

Sends SIGTERM unless force is True (SIGKILL on Unix; TerminateProcess on Windows regardless of force). Returns True if the port became free.

Raises:

Type Description
PortlyPermissionError

If we lack permission to kill the process.

PortlyPortError

If the process(es) could not be killed for another reason.

Return process info for each port in ports (None when free).