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.
pip install port-forVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates finding an ephemeral available port using `available_ports` and managing persistent port assignments with `PortFor`. `PortFor` ensures that once a port is assigned to an ID, subsequent requests with the same ID return that same port.
Use a unique identifier with `PortFor` for each service that requires a stable port, or use `available_ports` for truly ephemeral port needs.
For critical multi-process initial port assignments with the same ID, consider external locking or a dedicated port server/coordinator to prevent potential race conditions, or ensure each process requests a unique ID.
Always use the return value of `forward_port` for the actual assigned port, rather than assuming `default_port` was used.
Install the library using pip: `pip install port-for`. If a typo, correct the import to `import port_for`. If shadowing, rename your script file.
Consult the `port-for` documentation for the correct function names and their usage. For finding an available port, use `port_for.available_local_port()`.
Allow `port-for` to select a random available port by calling `port_for.available_local_port()` without the `port` argument. If you need a specific port, ensure no other application is using it, or use `netstat` (or `lsof` on Linux/macOS) to identify and stop the conflicting process.
Replace the `id` argument with `binding`. For example, change `port_for.available_local_port(id='my_service')` to `port_for.available_local_port(binding='my_service')`.