port-for: Local TCP Ports Management
Port-for is a utility that assists with local TCP ports management. It can identify an unused TCP localhost port and maintain an association with a given identifier, ensuring that subsequent requests for the same ID return the same port number. The current version is 1.0.0, primarily functioning as a local port management tool.
Warnings
- gotcha The `PortFor` class is designed for *persistent* port assignments tied to an identifier, not for finding a random available port each time. If you need a new, unassociated port, you must use a new ID or `available_ports`.
- gotcha While `port-for` aims to manage local port persistence, in highly concurrent multi-process environments, there's a theoretical race condition when *initially* assigning a port for a new ID. If multiple processes simultaneously attempt to call `forward_port` with the *same new ID* for the very first time, careful synchronization might be required externally, as `port-for` primarily handles persistence within a single management context.
- gotcha The `forward_port` method takes a `default_port` argument. This is a *suggestion* for the desired port, not a guarantee. If the `default_port` is already in use (or was assigned to another ID), `port-for` will find another available port. The returned port is what's assigned to the ID.
Install
-
pip install port-for
Imports
- available_ports
from port_for import available_ports
- PortFor
from port_for import PortFor
Quickstart
from port_for import available_ports, PortFor
# Find an ephemeral available port (context manager ensures release)
with available_ports(5000) as port:
print(f"Found available port (5000 or next): {port}")
# Use PortFor for persistent port assignment based on an ID
port_manager = PortFor()
# Assign a port for 'my-service' (will try 8000 first)
my_service_port = port_manager.forward_port("my-service", 8000)
print(f"Assigned port for 'my-service': {my_service_port}")
# Assign a port for 'another-service' (will try 9000 first)
another_service_port = port_manager.forward_port("another-service", 9000)
print(f"Assigned port for 'another-service': {another_service_port}")
# Subsequent calls with the same ID will return the same assigned port
same_service_port = port_manager.forward_port("my-service", 8000) # 8000 is a suggestion, not a requirement
print(f"Re-requested port for 'my-service' (should be {my_service_port}): {same_service_port}")
# To release a port (optional, happens on process exit by default)
port_manager.release("another-service")
print("Released port for 'another-service'")